gpt4 book ai didi

java - 功能接口(interface)eg-toString,equals中继承对象类方法有什么用

转载 作者:行者123 更新时间:2023-12-03 22:52:34 25 4
gpt4 key购买 nike

我发现以下代码,继承的 equals() 和 toString() 方法的用途是什么。

@FunctionalInterface
public interface FunInterface<T> {
// An abstract method declared in the functional interface
int test(T o1, T o2);

// Re-declaration of the equals() method in the Object class
boolean equals(Object obj);

String toString();
}

最佳答案

(重新)声明这种方法的主要原因是扩展和记录契约(Contract)。如果是 Comparator.equals(…) ,这不是那么明显,因为它没有指定那么多新闻。它说

This method must obey the general contract of Object.equals(Object). Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.

这是大多数人无论如何都会假设的。更糟糕的是,不覆盖 equals 也很好,如果不是说执行此协定的最佳方式,尤其是因为 JRE 类从不考虑比较器相等性。

要获得更好的覆盖方法示例,请考虑

List.equals(Object)

Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if Objects.equals(e1, e2).)

List.hashCode()

Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

int hashCode = 1;
for (E e : list)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());

This ensures that list1.equals(list2) implies that list1.hashCode()==list2.hashCode() for any two lists, list1 and list2, as required by the general contract of Object.hashCode().

这提供了一个扩展的契约,不能通过简单地使用从 java.lang.Object 继承的 equals(Object)hashCode() 方法来实现。不幸的是,一个接口(interface)不能强制它的实现类覆盖这些方法,但这不应该阻止它声明它来记录契约(Contract)。


当然,拥有这样的契约与将接口(interface)用作功能接口(interface)的意图不兼容,因为 lambda 表达式和方法引用不能覆盖从 java.lang 继承的方法.Object 提供更具体的实现。

但是 java.util.Comparator 是在 Java 2 中引入的,早在 Java 8 引入函数式接口(interface)的概念之前。如前所述,它的特殊之处在于我们仍然可以使用 Comparator 作为函数接口(interface),因为继承自 java.lang.Objectequals 实现很好关于为 java.util.Comparator.equals 指定的合约。

所以当设计新的接口(interface)打算用作功能接口(interface)时,你不应该声明与java.lang.Object相匹配的方法。

关于java - 功能接口(interface)eg-toString,equals中继承对象类方法有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695623/

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