Search code examples
javacomparator

How to check if a comparator can be used on an object of unknown type?


Say I'm implementing a sorted set in Java with a generic <T>, like a binary search tree. The set uses a Comparator<T> to order its elements. For simplicity, let's assume the comparator is always defined.

Most collections define contains(Object), where the argument is of type Object and not the collection's generic type T.

How is a method like this implemented? You can't use the comparator on the argument, because you don't know the argument's type. You can't even check if a cast is allowed.

I can only imagine two solutions, both bad:

  • The set has to be created with a Class<T> object so that I can check if the argument can be cast. But clearly Java's collections framework doesn't require this, so there must be a way around it.
  • Just do the cast and catch the ClassCastException that might result. This seems icky.

Solution

  • You can see it yourself in TreeMap.getEntryUsingComparator.

    Spoiler: it starts with

    K k = (K) key;
    

    So it will just throw ClassCastException as said in JavaDoc (thanks @yshavit).