Implementing The Serializable Interface


Implementing java.util.Comparator Interface

The Comparator interface is meant to be implemented by objects that will be used to impose a total ordering upon other objects. A total ordering is an ordering imposed upon a set of objects that is different from the natural ordering provided for by the implementation of the Comparable interface.

The Comparator interface declares two methods: 1) compare(Object o1, Object o2), and 2) equals(Object o). The compare method compares the two argument objects o1 and o2. Just like the Comparable’s compareTo() method, the compare() method should perform consistently with the equals() method. However, in this example, I will create a comparator class that can be used to sort Person objects by age. Example 23.12 gives the code for the PersonAgeComparator class.

Example 23.12: PersonAgeComparator.java

image from book
 1     import java.util.*; 1     import java.io.*; 2 3     public final class PersonAgeComparator implements Comparator, Serializable { 4        public final int compare(Object o1, Object o2){ 5          int result = 0; 6          if(((Person)o1).getAge() < ((Person)o2).getAge()) 7            result = -1; 8            else if(((Person)o1).getAge() == ((Person)o2).getAge()) 9                  result = 0; 10                 else if(((Person)o1).getAge() > ((Person)o2).getAge()) 11                   result = 1; 12          return result; 13        } 14 15        public final boolean equals(Object o){ 16          if(o == null) return false; 17          boolean is_equal = false; 18          if(o instanceof PersonAgeComparator){ 19             is_equal = true; 20          } 21          return is_equal; 22      } 23    } // end PersonAgeComparator
image from book

Referring to example 23.12 — the class is declared to be final so that it cannot be extended. It also implements the Serializable interface as recommended in the Java Platform API documentation. This is recommended because the comparator may be used to order serializable data structures. (If the collection is serialized, the comparator used to order the collection must be serialized along with it.) The compare() method takes two Object references as arguments. It casts each to the Person type and compares their ages using their getAge() methods. Now, let's see if this thing works! Example 23.13 gives a modified version of the CollectionTestApp program.

Example 23.13: CollectionTestApp.java (mod 1)

image from book
 1     import java.util.*; 2 3     public class CollectionTestApp { 4       public static void main(String[] args){ 5         List list = new ArrayList(); 6 7         list.add(new Person("Rick", "W", "Miller", 1963, 5, 6, Person.MALE)); 8         list.add(new Person("Debbie", "S", "Sears", 1986, 8, 3, Person.FEMALE)); 9         list.add(new Person("John", "L", "Thompson", 1978, 1, 4, Person.MALE)); 10        list.add(new Person("Riddic", "H", "Bean", 2001, 11, 15, Person.MALE)); 11        list.add(new Person("Gloria", "J", "Albright", 1922, 12, 2, Person.FEMALE)); 12        list.add(new Person("Zena", "P", "Warrior", 1968, 1, 26, Person.FEMALE)); 13        list.add(new Person("Shelly", "H", "Marshall", 1993, 7, 15, Person.FEMALE)); 14        list.add(new Person("Jessica", "A", "Simpson", 1912, 6, 3, Person.FEMALE)); 15        list.add(new Person("Peter", "R", "Rabbit", 1999, 4, 30, Person.MALE)); 16        list.add(new Person("Mohamad", "A", "Abbas", 1961, 5, 29, Person.MALE)); 17        list.add(new Person("Sapna", "P", "Gupta", 1988, 8, 11, Person.FEMALE)); 18        list.add(new Person("Marvin", "C", "Williams", 1945, 2, 18, Person.MALE)); 19        list.add(new Person("Kyle", "V", "Miller", 1954, 9, 13, Person.MALE)); 20        list.add(new Person("Joseph", "L", "Smith", 1963, 10, 23, Person.MALE)); 21        list.add(new Person("Nora", "G", "Jones", 1977, 11, 4, Person.FEMALE)); 22        list.add(new Person("Hedy", "E", "Lamarr", 1914, 2, 28, Person.FEMALE)); 23 24        for(Iterator i = list.iterator(); i.hasNext();){ 25           Person p = (Person)i.next(); 26           System.out.println(p.toString() + " " + p.getAge()); 27        } 28 29        Collections.sort(list, new PersonAgeComparator()); 30 31        System.out.println("--------------Sorted List--------------------"); 32        for(Iterator i = list.iterator(); i.hasNext();){ 33           Person p = (Person)i.next(); 34           System.out.println(p.toString() + " " + p.getAge()); 35        } 36      } 37    } // end CollectionTestApp
image from book

Referring to example 23.13 — a few modifications were made to the program. The format of the console output was changed slightly to include age information in addition to the standard Person.toString() text. The primary difference, however, is the use of the PersonAgeComparator class on line 29. A new PersonAgeComparator object is created using the new operator and used as the second argument to the Collections.sort() method. This causes the list of Person objects to be sorted according to age. Figure 23-8 gives the results of running this program.

image from book
Figure 23-8: Results of Running Example 23.13

Quick Review

The Comparator interface is implemented by a class of objects whose job it is to impose a total ordering upon another class of objects. It is suggested that the Comparator.compare() method’s behavior be consistent with the equals() method of the class upon which it is imposing order.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net