英文:
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 <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;
}
}
In the method signature
public static <T extends Object & Comparable<? super T>> T max(List<? extends T> 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?
专注分享java语言的经验与见解,让所有开发者获益!
评论