gpt4 book ai didi

java - 为什么 T 在 Collections.max() 签名中受 Object 限制?

转载 作者:IT老高 更新时间:2023-10-28 13:51:26 27 4
gpt4 key购买 nike

刚刚浏览了 Java 7 的 java.util.Collections 类的实现,看到了一些我不明白的东西。在 max 函数签名中,为什么 TObject 为界?

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();

while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}

max 如果省略了 Object 绑定(bind),似乎可以正常工作。

public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();

while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}

实际上是否存在边界产生影响的情况?如果是,请提供一个具体的例子。

最佳答案

两者的界限相同,但细微的差别。

 <T extends Object & Comparable<? super T>> 

这将导致 T成为Object正在删除。

 <T extends Comparable<? super T>>

这将导致 T成为Comparable正在删除。


在这种情况下,因为 .max早于 Java 5。我们可以在 this link 中看到Joachim 提供.max 的签名。在 Java 1.4.2 中是:

public static Object max(Collection coll)

如果我们使用 <T extends Comparable<? super T>>作为一个界限,我们的签名将是

public static Comparable max(Collection coll)

这会破坏 API。我找到了this page讨论将旧 API 转换为通用 API 并给出 .max作为一个具体的例子。

他们在这里解释了原因 max是这样定义的:

You also need to ensure that the revised API retains binary compatibility with old clients. This implies that the erasure of the API must be the same as the original, ungenerified API. In most cases, this falls out naturally, but there are some subtle cases. We'll examine one of the subtlest cases we've encountered, the method Collections.max(). As we saw in section More Fun with Wildcards, a plausible signature for max() is:

public static <T extends Comparable<? super T>> T max(Collection<T> coll) This is fine, except that the erasure of this signature is: public static Comparable max(Collection coll) which is different than the original signature of max(): public static Object max(Collection coll)

One could certainly have specified this signature for max(), but it was not done, and all the old binary class files that call Collections.max() depend on a signature that returns Object.

关于java - 为什么 T 在 Collections.max() 签名中受 Object 限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488357/

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