重写“等于”方法:如何弄清楚参数的类型? [英] Overriding "equals" method: how to figure out the type of the parameter?
问题描述
我想为参数化类覆盖 equals
方法。
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof Tuple))
return false;
元组< E> other =(Tuple E)obj;如果(!a0.equals(other.a0)&&!a0.equals(other.a1)){
return false;
if(!a1.equals(other.a1)&&!a1.equals(other.a0)){
return false;
}
返回true;
}
如何确保< E>
与其他
对象的 this
?
Class< E>
类型的引用来实现。然而,在我看来,平等测试应该是关于对象所表示的值,而不是值表达的具体类型。 例如,这是Collections API。 new ArrayList< String>()。equals(new LinkedList< Object>())
返回 true
。虽然这些类型有完全不同的类型,但它们表示相同的值,即一个空集合。就个人而言,应该两个元组 s(例如
(a,b)
)不相等,因为一个类型为 Tuple < ;字符串>
,而另一个是元组< $>< / code>?
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>
?
这篇关于重写“等于”方法:如何弄清楚参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!