声明类型通配符必须扩展Object有什么意义?

huangapple 未分类评论45阅读模式
英文:

What is the point of stating that a type wildcard must extend Object?

问题

Oracle提供了一些关于Java泛型的问题,附带答案。这是问题8。

编写一个通用方法,在列表的范围[begin,end)中找到最大的元素。

解决方案

import java.util.*;

public final class Algorithm {
    public static <T extends Object & Comparable<? super T>>
        T max(List<? extends T> list, int begin, int end) {

        T maxElem = list.get(begin);

        for (++begin; begin < end; ++begin)
            if (maxElem.compareTo(list.get(begin)) < 0)
                maxElem = list.get(begin);
        return maxElem;
    }
}

在方法签名中

public static <T extends Object & Comparable<? super T>> T max(List<? extends T> list, int begin, int end)

声明T必须扩展Object的意义是什么?难道不是所有的东西都这样做吗?这是多余的吗?

英文:

Oracle provides some java generics questions with answers. This is problem 8.

> Write a generic method to find the maximal element in the range
> [begin, end) of a list.

solution

import java.util.*;

public final class Algorithm {
    public static &lt;T extends Object &amp; Comparable&lt;? super T&gt;&gt;
        T max(List&lt;? extends T&gt; list, int begin, int end) {

        T maxElem = list.get(begin);

        for (++begin; begin &lt; end; ++begin)
            if (maxElem.compareTo(list.get(begin)) &lt; 0)
                maxElem = list.get(begin);
        return maxElem;
    }
}

In the method signature

public static &lt;T extends Object &amp; Comparable&lt;? super T&gt;&gt; T max(List&lt;? extends T&gt; list, int begin, int end)

What is the point of stating that T must extend Object? Doesn't everything do that anyway? Is this redundant?

huangapple
  • 本文由 发表于 2020年4月8日 01:58:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61086398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定