Java hashcode from multiple fields
•
Java
In view of such a class:
class MyObject { private String id1; private String id2; @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MyObject)) { return false; } MyObject other = (MyObject) o; return id1.equals(other.id1) || id2.equals(other.id2); } }
Note that equality does not depend on two field matches, both fields are valid What is the appropriate hashcode implementation for this class?
Solution
This is not an effective implementation of equals
Specifically, it violates the transitivity requirement
Therefore, in addition to having all instances have the same hash code, you cannot "correctly" implement hashcode
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码