(I posted this in the collection forum, but it was suggested I should take it here instead.)
I've written an OrderedPair element class, (OrderedPair<K,V>), so I can have a set of ordered pairs.
To get the container to treat OrderedPairs as values instead of objects, I had to override OrderedPair<K,V>.equals(Object) (as hashCode too).
So I've written the equals(Object) below in the naive way and I'm now getting warnings about an unsafe cast at line (a) and an unsafe assignemtn at line (b).
I do understand
why this is a problem, but I'm not sure what the best solution is.
How does one ask about instanceof for the otherObject, and how does one cast an Object to an OrderedPair<K,V> in a safe way?
public boolean equals (Object otherObject) {
if (otherObject == null || ! (otherObject instanceof OrderedPair<K,V>)) { //line (a)
return false;
} else {
OrderedPair<K,V> otherPair = (OrderedPair<K,V>) otherObject; // line (b)
return this.key.equals(otherPair.key) && this.value.equals(otherPair.value);
}
}
or, more to the point, how does one write a version of equals(Object) for a generic class?
It seems that this overriding of equal will have to be done for many generic element types, so there must be some approach that is safe, yes?
It was pointed out to me that AbstractMap does something similar