gpt4 book ai didi

java - 为什么Collection接口(interface)有equals()和hashCode()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:17 25 4
gpt4 key购买 nike

为什么 Collection接口(interface)有 equals(Object o)hashCode(),假设任何实现都默认有那些(继承自 Object)?

最佳答案

来自Collection JavaDoc :

While the Collection interface adds no stipulations to the general contract for the Object.equals, programmers who implement the Collection interface "directly" (in other words, create a class that is a Collection but is not a Set or a List) must exercise care if they choose to override the Object.equals. It is not necessary to do so, and the simplest course of action is to rely on Object's implementation, but the implementor may wish to implement a "value comparison" in place of the default "reference comparison." (The List and Set interfaces mandate such value comparisons.)

The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both the Set and List interfaces.)

While the Collection interface adds no stipulations to the general contract for the Object.hashCode method, programmers should take note that any class that overrides the Object.equals method must also override the Object.hashCode method in order to satisfy the general contract for the Object.hashCode method. In particular, c1.equals(c2) implies that c1.hashCode()==c2.hashCode().

关于java - 为什么Collection接口(interface)有equals()和hashCode()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45630264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com