Java – HashMap can only be copied through hashcode()

See English answers > Why do I need to override the equals and hashcode methods in Java? 28

Therefore, whether K is "equivalent" to key or not, K must be = = to key

Can you change this behavior so that only hashcode () is used?

Solution

No, this is not true, because @ Kevin Wallis has observed it HashMap uses hashcode () to identify the correct hash bucket, and uses equals () instead of = = to compare keys belonging to the same bucket Meaningful types, in which different instances are equivalent, should be described by their equals () methods, and standard library types (such as string and integer) actually do so When the key is of this type, you do not have to use the same object to retrieve the value storing it from the HashMap

On the other hand, types that do not have meaning, where different instances are equivalent, should not, and usually do not override equals () (or hashcode ()) The implementation inherited from object produces the same result as the = = operator, which makes it possible and reasonable to use these objects as HashMap keys or store them in HashSet, at least in some cases

It is impossible to change the behavior of HashMap in this regard If you can do so, the generated map will not fulfill the map contract correctly However, you can implement your own map like classes that behave as you described, or you can create a wrapper class to use as an alternative key type

Example key classes:

class HashEquivalenceKey<T> {
    private final T object;

    public HashEquivalenceKey(T object) {
        this.object = object;
    }

    public int hashCode() {
        return ((o == null) ? 0 : object.hashCode());
    }

    public boolean equals(Object o) {
        return ((o != null) && (this.hashCode() == o.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
分享
二维码
< <上一篇
下一篇>>