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.
CodePudding user response:
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.)
