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:


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