假设我有一个像这样的通用容器类型:
public final class Container<T> {
public final T t;
public Container(final T t) {
this.t = t;
}
}
我想实现 equals 这样通过:
final Container<Object> a = new Container<>("Hello");
final Container<String> b = new Container<>("Hello");
assertNotEquals(a, b);
实例a
和b
应该是不同的,因为它们的类型参数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;
}
我希望我需要为 T
存储某种 token 。
如何为泛型类型实现 equals?
This不回答问题。
最佳答案
您可以稍微修改 Container 类并添加此字段:
public final Class<T> ct;
然后用那个和等号覆盖
System.out.println(a.equals(b));
将返回 false
因为 equals 方法将检查 Class<String>
对比Class<Object>
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;
}
}
关于java - 如何为泛型类型实现 equals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44306944/