我刚刚遇到了Java泛型教程,它似乎使用原始int,float等作为扩展Comparable的对象
public class MaximumTest {
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x; // assume x is initially the largest
if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}
if(z.compareTo(max) > 0) {
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main(String args[]) {
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum("pear", "apple", "orange"));
}
}
原始可以以某种方式成为可比对象吗?
答案 0 :(得分:4)
原语将被自动装箱到实现Comparable
的包装器对象。
int val = 3;
将成为Integer
autoboxing and unboxing java
答案 1 :(得分:2)
正式地,这是由于您的Java编译器需要如何考虑重载解析。如果找不到类型的重载,则会考虑加宽类型的重载。如果不存在这样的重载,则考虑使原始类型自动装箱到相应的盒装类型。使用泛型指定的函数是合适的候选者。
在您的情况下,适当的重载
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
可以找到,编译成功。
根据JLS 15.12.2选择具有此优先级的函数:
(取自我的回答Why is f(Double x) a better match than f(double... x)?)