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