This example illustrates the fact that the objects of a collection have to be mutually comparable. If not a ClassCastException is returned by compare. Book page 583.
In this example if the object you put in the TreeSet is the a String, the comparison is made on name of the class...
package treesets;
public class StrangeClass implements Comparable <Object'> {
Object aStrangeObject;
String name;
StrangeClass(Object o) {
aStrangeObject = o;
if (o instanceof String) {
name = (String) o;
} else {
name = o.getClass().getName();
}
}
public int compareTo(Object o) {
return name.compareTo(((StrangeClass)o).name);
}
public String toString() {
if (aStrangeObject instanceof String) {
return (String) aStrangeObject;
}
return name;
}
}
package treesets;
import java.util.Set;
import java.util.TreeSet;
public class TestStrangeClass {
public static void main(String[] args) {
boolean[] ba = new boolean[5];
//Set s = new HashSet();
Set s = new TreeSet<StrangeClass'>();
ba[0] = s.add(new StrangeClass(new String("c")));
ba[1] = s.add(new StrangeClass(new Integer(42)));
ba[2] = s.add(new StrangeClass(new String("b")));
ba[3] = s.add(new StrangeClass("a"));
ba[4] = s.add(new StrangeClass(new Object()));
for (int x = 0; x < ba.length; x++) {
System.out.println(ba[x]);
}
System.out.println("Display : ");
for (Object o : s) {
System.out.println(o);
}
}
}
run:
true
true
true
true
true
Display :
a
b
c
java.lang.Integer
java.lang.Object
No comments:
Post a Comment