Here's my code:
public static void main(String[] args){
TreeSet<Dog> d = new TreeSet<Dog>();
d.add(new Dog());
System.out.println(d.size());
}
class Dog{
}
As you can see, the Dog
class is not a Comparable
object and I sure did not specify a Comparator
to be used for sorting. How does this snippet of code run without exceptions? It printed out 1
.
I tried adding another Dog
to the TreeSet and it threw a ClassCastException
as expected.
EDIT: I'm using Java 6
There was a change added in Java 7 to fix this. It was an error.
Due to an error in
java.util.TreeMap
, it was previously possible to insert invalid null elements and elements not implementingComparable
into emptyTreeMap
s andTreeSet
s. Only a single invalid element could be inserted into the emptyTreeMap
s orTreeSet
s; additional elements would cause the expectedNullPointerException
orClassCastException
. Most other operations upon the collection would also fail. As of JDK 7, inserting an invalid null element or an element not implementingComparable
into an emptyTreeMap
orTreeSet
throws aNullPointerException
.
(TreeSet
is implemented with a TreeMap
as its underlying data structure.)