// COntains solution to exercise 5.2 package dk.itu.oop.lecture4exercises; import java.util.*; class PersonExercises{ public static void main(String[] args) { SortedSet ss = new TreeSet(); ss.add(new Person("Michael", "Jackson", 12)); ss.add(new Person("Michael", "Duglas", 53)); ss.add(new Person("Donald", "Duck", 114)); ss.add(new Person("Lone", "Jespersen", 29)); print(ss.iterator()); // ex b - putting them in a set with another way of comparing.. // notice we cannot just change the comparator run time SortedSet ns = new TreeSet(new PersonAgeCompare()); ns.addAll(ss); print( ns.iterator() ); // ex d - toying with a LinkedList LinkedList ll = new LinkedList(ns); // new list filled with the old elements // ex e - sort the list in two ways.. Collections.sort(ll); print(ll.listIterator()); Collections.sort(ll, new PersonAgeCompare()); print(ll.listIterator()); } // Auxiliary method for printing all elements using // an iterator. private static void print(Iterator i) { while(i.hasNext()) System.out.println(i.next()); System.out.println("---"); } } class Person implements Comparable { String firstname, lastname; int age; Person(String firstname, String lastname, int age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } public int compareTo(Object o) { if(o instanceof Person) { int res = 0; Person p = (Person) o; res = firstname.compareTo(p.firstname); if ( res != 0) return res; res = firstname.compareTo(p.lastname); if ( res != 0) return res; res = age - p.age; return res; } else throw new Error("Can only compare Person with other Persons..."); } public String toString() { return firstname + " " + lastname + " " + age;} } // ex b class PersonAgeCompare implements Comparator { public int compare(Object o1, Object o2) { Person p1 = (Person) o1, p2 = (Person) o2; // System.out.println("called.." + p1 + " " + p2); return p1.age - p2.age; } } /* 2c The differences in the approaches are - Comparing in a comparator is more restricted, since access to private fields are no longer permitted. (the issue is similar for protected / package fields). - The external comparator solution is much more generic, hence the SortedTree code is much more reusable. This stems from the fact, that several compare methods can exist for the same set of data. */