Java 如何为泛型类型实现equals?
假设我有这样一个通用容器类型:Java 如何为泛型类型实现equals?,java,generics,type-erasure,Java,Generics,Type Erasure,假设我有这样一个通用容器类型: public final class Container<T> { public final T t; public Container(final T t) { this.t = t; } } 我希望我需要为T存储某种令牌 如何为泛型类型实现equals 没有回答这个问题 您可以稍微修改容器类并添加此字段: public final Class<T> ct; 将返回false,因为equa
public final class Container<T> {
public final T t;
public Container(final T t) {
this.t = t;
}
}
我希望我需要为T
存储某种令牌
如何为泛型类型实现equals
没有回答这个问题 您可以稍微修改容器类并添加此字段:
public final Class<T> ct;
将返回false
,因为equals方法将检查Class
vsClass
类容器{
公开期末考试;
公开期末班;
公共集装箱(最终T级,ct级){
t=t;
this.ct=ct;
}
@凌驾
公共int hashCode(){
最终整数素数=31;
int结果=1;
result=(prime*result)+(ct==null)?0:ct.hashCode();
result=(prime*result)+(t==null)?0:t.hashCode();
返回结果;
}
@凌驾
公共布尔等于(对象obj){
if(this==obj)
返回true;
if(obj==null)
返回false;
如果(getClass()!=obj.getClass())
返回false;
容器其他=(容器)对象;
如果(ct==null){
如果(other.ct!=null)
返回false;
}如果(!ct.equals(other.ct))
返回false;
如果(t==null){
if(other.t!=null)
返回false;
}如果(!t.equals(other.t))
返回false;
返回true;
}
}
它实际上与擦除无关。如果使用数组,其中没有擦除,比如Object[]a={“Hello”};字符串[]b={“Hello”}
,a[0]。equals(b[0])
仍将返回true
。equals
操作使用对象的运行时类型。是否有方法消除新容器(“a”,String.class)
的锅炉板?对于Container
,这仍然有效吗?您应该熟悉对象.hash()
,它与hashCode()
的实现完全相同,因此您的方法变成了返回对象.hash(ct,t)代码>
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof Container<?>) {
final Container<?> other = (Container<?>)obj;
return Objects.equals(this.t, other.t);
}
return false;
}
public final Class<T> ct;
System.out.println(a.equals(b));
class Container<T> {
public final T t;
public final Class<T> ct;
public Container(final T t, Class<T> ct) {
this.t = t;
this.ct = ct;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((ct == null) ? 0 : ct.hashCode());
result = (prime * result) + ((t == null) ? 0 : t.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (ct == null) {
if (other.ct != null)
return false;
} else if (!ct.equals(other.ct))
return false;
if (t == null) {
if (other.t != null)
return false;
} else if (!t.equals(other.t))
return false;
return true;
}
}