如何为泛型类型实现 equals?

How do I implement equals for generic types?

假设我有一个像这样的通用容器类型:

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);

实例 ab 应该不同,因为它们的类型参数 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 存储某种令牌。

如何为泛型类型实现 equals?


This 不回答问题。

您可以稍微修改 Container class 并添加此字段:

public final Class<T> ct;

然后用等号覆盖

System.out.println(a.equals(b));

将 return 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;
    }

}