Pregunta

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

¿Fue útil?

Solución

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.)

Otros consejos

According to the javadoc that's the expected behavior, it will throw a ClassCastException only if the new element cannot be compared with the current elements in the set:

ClassCastException - if the specified object cannot be compared with the elements currently in this set

EDIT

However, this is valid for JSE6, apparently the javadoc for TreeSet in JSE7 is out of date, since as @SotiriosDelimanolis points out, this problem was solved for JSE7.

Very nice trick. You are not getting exception because you didn't added more than one object as only then you need to compare the object which will end up throwing exception.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top