001package edu.pdx.cs410J.examples; 002 003import edu.pdx.cs410J.lang.*; 004import java.util.*; 005 006/** 007 * This class is a <code>Comparator</code> that compares 008 * <code>Object</code>s based on the name of their classes. 009 */ 010public class ClassComparator implements Comparator<Object> { 011 public int compare(Object o1, Object o2) { 012 String name1 = o1.getClass().getName(); 013 String name2 = o2.getClass().getName(); 014 015 // Take advantage of String's compartTo method 016 return name1.compareTo(name2); 017 } 018 019 /** 020 * Create a bunch of object and store them in a set using a 021 * <code>ClassComparator</code>. 022 */ 023 public static void main(String[] args) { 024 Set<Object> set = new TreeSet<Object>(new ClassComparator()); 025 set.add("Hello"); 026 set.add(new Cow("Betty")); 027 set.add(new Vector()); 028 set.add(new Ant("Richard")); 029 030 // Print out the set 031 Iterator iter = set.iterator(); 032 while (iter.hasNext()) { 033 Object o = iter.next(); 034 String s = o + " (" + o.getClass().getName() + ")"; 035 System.out.println(s); 036 } 037 } 038}