Search code examples
javasetocpjp

Java: Possible to add 1 non-Comparable object to a TreeSet?


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


Solution

  • 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 implementing Comparable into empty TreeMaps and TreeSets. Only a single invalid element could be inserted into the empty TreeMaps or TreeSets; additional elements would cause the expected NullPointerException or ClassCastException. Most other operations upon the collection would also fail. As of JDK 7, inserting an invalid null element or an element not implementing Comparable into an empty TreeMap or TreeSet throws a NullPointerException.

    (TreeSet is implemented with a TreeMap as its underlying data structure.)