java是不是比较原始_java – 原始int也是可比较的吗?

我刚刚遇到了一个Java泛型教程,似乎使用原始int,float等作为扩展Comparable的对象

public class MaximumTest {

// determines the largest of three Comparable objects

public static > 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"));

}

}

原始可以以某种方式成为可比对象吗?

解决方法:

形式上,这是由于您的Java编译器需要如何考虑重载解析.如果找不到类型的重载,则会考虑扩大类型的重载.如果不存在这样的重载,则考虑将原始类型自动装箱到相应的盒装类型的过载.使用泛型指定的函数是合适的候选者.

在你的情况下,适当的过载

public static< T extends Comparable< T>> T最大值(T x,T y,T z)

可以找到,编译成功.

根据JLS 15.12.2,使用此优先级选择函数:

>类型加宽

>自动拳击

>变量参数

标签:java,generics

来源: https://codeday.me/bug/20190823/1701681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值