Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
16. String Sorting Program
Answer:
Yes. So an array of String
references can be sorted.
String Sorting Program
Here is a program that demonstrates how sort()
is used with an array of String
references.
Notice the use of the for-each loops.
The output of the program is:
Scrambled array: bat fox gnu eel ant dog fox gnat
Sorted array: ant bat dog eel fox fox gnat gnu
import java.util.Arrays; class ArrayDemoTwo { public static void main ( String[] args ) { String[] animals = {"bat", "fox", "gnu", "eel", "ant", "dog", "fox", "gnat" }; System.out.print("Scrambled array: "); for ( String anm : animals ) System.out.print( anm + " "); System.out.println(); Arrays.sort( animals ); System.out.print("Sorted array: "); for ( String anm : animals ) System.out.print( anm + " "); System.out.println(); } } |
Question 16:
To use sort()
with a class that you define, what interface must that class implement?