import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import javax.swing.JOptionPane; /** * COP3337 Example * * @author Bill Kraynek */ public class Example2A { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { ArrayList people = new ArrayList(); Scanner fileScanner = new Scanner( OpenFiles.getNameAndOpenInput() ); 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 main public static 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. static 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. static class idNumberOrder implements Comparator { public int compare(Person personA, Person personB) { return personA.getIdNumber().compareTo(personB.getIdNumber()); } // end compare } // end idNumberOrder } // end Example2A