猿问

方法的冗余声明

我想知道这两种方法的声明是否存在逻辑差异:

示例1

public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)

示例2

public static <T extends Comparable<? super T>> T findMax(List<T> list)

有人告诉我,这部分<? extends T>相当于<T>第一个示例中的通配符,并且通配符是多余的,他建议我使用第二个示例中的代码。是对的吗?


繁星coding
浏览 106回答 1
1回答

ABOUTYOU

他们不一样。向这个“某人”展示这个反证:)class Scratch{&nbsp; &nbsp; interface A extends Comparable<A> {}&nbsp; &nbsp; interface B extends A {}&nbsp; &nbsp; public static <T extends Comparable<? super T>> T findMax(List<? extends T> list)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; public static <T extends Comparable<? super T>> T findMax2(List<T> list)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; List<B> listOfBs = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; A foo = Scratch.<A>findMax(listOfBs);&nbsp; // fine&nbsp; &nbsp; &nbsp; &nbsp; A bar = Scratch.<A>findMax2(listOfBs); // compiler error&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答