The examples below show how objects which are Comparable can use the sort method in the array class.
/** * This example String objects in an array get sorted. */ import java.util.Arrays; public class SortingStrings { public static void main(String[] args) { String animals[] = new String[4]; animals[0] = "weasel"; animals[1] = "kangaroo"; animals[2] = "aardvark"; animals[3] = "chipmunk"; for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } /*** * The method sort is in the Array class. The sort method can sort * any set of objects that implements the Comparable interface by * having a compareTo method. * * Strings can be sorted since they are Comparable. */ Arrays.sort(animals); for (int i=0; i<4; i++) { System.out.println("animal " + i + " : " + animals[i]); } } }
A second example...
/** * This example shows sorting of an array of Person objects. * Make sure you understand how it works. */ public class Person implements Comparable { private String firstName; private String lastName; private int age; public Person(String first, String last, int ageOf) { firstName = first; lastName = last; age = ageOf; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public void printPerson() { System.out.println(firstName + ", " + lastName + ", " + age); } public int compareTo(Object anotherPerson) { // Note that anotherPerson must be cast as a Person in order to // use the method getLastName. String otherLast = ((Person)anotherPerson).getLastName(); // uses the compareTo method in the String class return lastName.compareTo(otherLast); } }
import java.util.Arrays; /** * Note that the array of type Person is able to be sorted * because Person implements the Comparable interface. */ public class SortingPeople { public static void main(String[] args) { Person[] persons = new Person[6]; persons[0] = new Person("Art", "Vandelay", 56); persons[1] = new Person("Carl", "Farbman", 45); persons[2] = new Person("Dr.", "VanNostrand", 48); persons[3] = new Person("Joe", "Divola", 50); persons[4] = new Person("Izzy", "Mandelbaum", 75); persons[5] = new Person("Jackie", "Chiles", 49); System.out.println("\nBefore Sort ..."); for (int i=0; i< persons.length; i++) { persons[i].printPerson(); } Arrays.sort(persons); System.out.println("\nAfter Sort ..."); for (int i=0; i< persons.length; i++) { persons[i].printPerson(); } } }