I'm trying to override equals
method for a parameterized class.
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Tuple))
return false;
Tuple<E> other = (Tuple<E>) obj; //unchecked cast
if (!a0.equals(other.a0) && !a0.equals(other.a1)) {
return false;
}
if (!a1.equals(other.a1) && !a1.equals(other.a0)) {
return false;
}
return true;
}
How can I make sure that <E>
of the other
object is the same as this
?
You can do it by retaining a reference to Class<E>
type. However, in my opinion, equality tests should be about the values the objects represent rather than the concrete types the values get expressed.
A classic example of this is the Collections API for example. new ArrayList<String>().equals(new LinkedList<Object>())
returns true
. While these have completely different types, they represent the same value, namely "an empty collection".
Personally, should two Tuple
s that represent the same data (e.g. ("a", "b")
) be not equal, because one is of type Tuple<String>
while the other is Tuple<Object>
?