Mar 16

Have you ever used TreeSet in Java? Let’s say we have a class called AClass. It only inherits from Object and doesn’t implement any interface. Now I want to use the following code snippet to add a collection of AClass to a TreeSet:

TreeSet treeSet = new TreeSet();
treeSet.addAll(listOfAClass)

What happens when you run this piece of code? You get a ClassCastException! Why? Because if you don’t supply a Comparator to the TreeSet, it by default thinks that the element you are adding implements Comparable. It just blindly tries to cast whatever you put in it to Comparable. This is not very nice, is it? Shouldn’t it prevent me from adding element that’s not Comparable in the first place? Exception should be part of the interface. Yes, there is the API and source code I can look at. But in the world of code completion, people rarely do that. An appropriate exception would have been a lot better.

2 Responses to “Exception is part of the interface”

  1. Jeff Perrin says:

    Java collections suck ass. I especially hate addAll on List and how it returns a boolean instead of another instance of List. And how useful functions like sorting use a static Collection method. And how there’s no useful filtering functions like find(Specification spec), or conversion functions like convertAll(ConversionCommand cmd).

  2. simon says:

    I totally agree with you. While they spent so much time introducing half-baked features like Generic, they should have paid more attention to improving existing ones.

Leave a Reply

preload preload preload