Search code examples
javagenericsclasscastexceptioninstanceof

ClassCastException vs instanceOf in Generic Collections


I have a class that implements Collection<E>.

When I check if my collection contains an item the interface's method give a parameter of object, when it's have to be an <E>

Do you think it's "normal" to write this code:

@Override
public boolean contains(Object o)
{
    E item;
    try
    {
        item=(E) o;
    }
    catch (ClassCastException e)
    {
        return false;
    }
    //check if contains "item"
}

I know that normally it's a terrible idea to check the type of an object with try,catch, but in a generic collection I can't check with instanceOf and I don't find a better solution.


Solution

  • From the javadoc it says:

    Throws: ClassCastException - if the type of the specified element is incompatible with this collection (optional)

    So it is perfectly acceptable to code it like this:

        @Override
        public boolean contains(Object o) {
            T item = (T) o;
            // ...
        }
    

    and if the cast fails a ClassCastException is thrown.

    You certainly should not hide that exception and quietly return false - that could leave many potential bugs in the user's code.