There is a topic about implementing a DoublyLinkedList, where the generic type T impements Comparable<T>. Now, I made my own implementation that I found a bit neater, althoud required some more code, but I found it a pity to have that generic having to implement Comparable. So I thought about a TreeSet, where you either use the natural comparing or you specifu a Comparator. I tried this, but I could not get it to work. I tried:
But that does not work. How can I get this to work?
There are three kinds of actuaries: those who can count, and those who can't.
Yeah, for the first use case you can use a type witness, but personally I prefer to type my variable explicitly and let type inference work its magic on the factory method:
TreeSet<E> is really just a thin wrapper around a TreeMap<E, Object>, where the values are always the same instance and ignored by the wrapper set. For instance, when you call treeSet.add(value), the call is delegated to treeMap.put(value, DUMMY).
TreeMap provides no fail-fast behavior at all. TreeMap uses a null comparator when you use the parameterless constructor. When you call TreeMap.put() it performs an explicit null check on the comparator field, and if it is null, it casts the key to Comparable<? super K>. This will cause a ClassCastException if the key is not Comparable.
When there's already another entry in the map, it calls compareTo() on the key and the existing entry's key, which will also throw a ClassCastException if the two are not actually comparable to each other.
Don't blame the designers of the collection framework though. TreeMap has been around since Java 1.2, whereas generics were added in Java 5.0.