import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Comparator; import java.util.StringTokenizer; import java.util.Collections; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class Example4A { public Example4A() throws IOException { ArrayList people = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader("people.data")); Scanner fileScanner = new Scanner(in); while( fileScanner.hasNext() ) { Scanner s = new Scanner(fileScanner.nextLine()); String idNumber = s.next(); String first = s.next(); String last = ""; while( s.hasNext() ) { last += s.next() + " "; } // end while Person aPerson = new Person(idNumber,first,last); // add aPerson to the end of the ArrayList people.add(aPerson); } // end while // The Collections class has a static method sort. // sort takes an ArrayList paramenter // The objects in the ArrayList must be Comparable // The ArrayList is sorted according to the natural comparator Collections.sort(people); display(people,"The names in \"natural\" order are:\n"); // The Collections class has a second static method sort. // This sort takes an ArrayList paramenter and a Comparator parameter // The ArrayList is sorted according to the Comparator Collections.sort(people,new NameLengthOrder()); display(people,"The names in first name length order are:\n"); Collections.sort(people,new idNumberOrder()); display(people,"The names in idNumber order are:\n"); } // end Example4A() public static void main(String[] args) throws IOException { new Example4A(); System.exit(0); } // end main public void display(ArrayList a, String title) { String out = title + "\n"; for( int i = 0; i < a.size(); i++ ) { // the toString() method is automatically called on // a.get(i) since we are concatenating to a String // the "correct" toString() method is called // because of polymorphism out += a.get(i) + "\n"; } // end for JOptionPane.showMessageDialog(null,out); } // end display // Comparator is an interface with one method to implement, the compare method. // This class implements compare so the order is by first name length. class NameLengthOrder implements Comparator { public int compare(Person personA, Person personB) { int difference = personB.getFirstName().length() - personA.getFirstName().length(); if( difference != 0 ) return difference; // if no difference in name length compare "naturally" return personA.compareTo((personB)); } // end compare } // end NameLengthOrder // This class implements compare so the order is by idNumber. class idNumberOrder implements Comparator { public int compare(Person personA, Person personB) { return personA.getIdNumber().compareTo(personB.getIdNumber()); } // end compare } // end idNumberOrder } // end Example4A