How do I implement equals for generic types?

Viewed 1391

Suppose I have a generic container type like this:

public final class Container<T> {

    public final T t;

    public Container(final T t) {
        this.t = t;
    }
}

I want to implement equals such that this passes:

final Container<Object> a = new Container<>("Hello");
final Container<String> b = new Container<>("Hello");

assertNotEquals(a, b);

The instances a and b should be different because their type parameter T is different.

However, due to erasure, this is tricky to do. This implementation, for example, is incorrect:

@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;
}

I expect that I will need to store some kind of token for T.

How do I implement equals for generic types?


This does not answer the question.

1 Answers
Related