Search code examples
javacollectionscastinghashtable

If Hashtable<E, ?>.containsKey(Object o) returns true for a certain object, am I safe to cast that Object to E?


For example, if I am implementing my own Collection<E> that uses a Hashtable<E, Integer> as its underlying data structure, I will implement remove(Object o), but o is not an E, it's an Object. But, if it returns true for containsKey(o), then am I safe to assume that casting o to E is going to succeed?

@Override
public boolean remove (@NotNull final Object o)
{
    if(underlyingHashTable.containsKey(o))
    {
        @NotNull final E item = (E) o;
        
    }
}

The IDE highlights the cast to (E) o as unchecked but I'm wondering if my assumption is sane & safe.


Solution

  • This is not strictly safe, even though, as you guess, it's usually fine.

    For example, if you had a Hashtable<LinkedList<String>, Integer>, and did containsKey(myArrayList), it could return true -- because it's legal for LinkedList.equals(ArrayList) to return true (and, in fact, it's mandated by the List interface).

    (This is among the reasons that Map.get takes an Object, not a K.)