问题描述
我希望我的 EqualTester
泛型类调用其重载的 equals(...)
方法泛型参数,但它似乎调用 Object.equals
来代替。这里是我的测试代码:
import junit.framework.TestCase;
public class EqualityInsideGenerics extends TestCase {
public static class EqualTester< V> {
public boolean check(V v1,V v2){
return v1.equals(v2);
}
}
public static class K {
private int i;
private Object o;
public K(Object o,int i){
this.o = o;
this.i = i; $($)
$ b public boolean equals(K k){
return((k.o!= null&& k.o.equals(o))|| o == null)&& (k.i == i);
}
};
public void testEqual(){
K k1 = new K(null,0);
K k2 = new K(null,0);
assertTrue(k1.equals(k2)); // This this ok
EqualTester< K> tester = new EqualTester< K>();
assertTrue(tester.check(k1,k2)); //这一个KO!
$ b 请解释为什么这不起作用,我该如何改变我的 EqualTester
类?
是因为 K
实际上并没有覆盖Object.equals()方法(因为该参数没有正确的类型)?
谢谢。
解决方案代码为 public boolean equals(Object k)
,然后转换为 k
。
现在,您只需重载equals方法。
添加 @Override
注释到方法。
重写方法签名时必须完全匹配。
I'd like my EqualTester
generic class to call the overridden equals(...)
method of its generic parameter, but it seems to call Object.equals
instead. Here is my test code:
import junit.framework.TestCase;
public class EqualityInsideGenerics extends TestCase {
public static class EqualTester<V> {
public boolean check(V v1, V v2) {
return v1.equals(v2);
}
}
public static class K {
private int i;
private Object o;
public K(Object o, int i) {
this.o = o;
this.i = i;
}
public boolean equals(K k) {
return ((k.o != null && k.o.equals(o)) || o == null) && (k.i == i);
}
};
public void testEqual() {
K k1 = new K(null, 0);
K k2 = new K(null, 0);
assertTrue(k1.equals(k2)); // This one ok
EqualTester<K> tester = new EqualTester<K>();
assertTrue(tester.check(k1, k2)); // This one KO!
}
}
Could you please explain why this does not work, and how I could change my EqualTester
class?
Is it because K
does not actually override the Object.equals() method (because the parameter does not have the correct type)?
Thanks.
解决方案 You need to code as public boolean equals(Object k)
, and then cast to k
.
Right now you are just overloading the equals method.
It's also useful to add @Override
annotation to the method.
When overriding the method signature must match exactly.
这篇关于在泛型类中使用equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!