Java 原始int也是可比的吗?

Java 原始int也是可比的吗?,java,generics,Java,Generics,我刚刚遇到了一个Java泛型教程,它似乎使用了原语int、float等作为扩展对象 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 ini

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

    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"));
   }
}
公共类最大测试{
//确定三个可比较对象中最大的一个
公共静态T最大值(T x,T y,T z){
T max=x;//假设x最初是最大的
如果(y.与(最大值)>0相比){
max=y;//y是迄今为止最大的
}
如果(z.compareTo(max)>0){
max=z;//现在z是最大的
}
return max;//返回最大的对象
}
公共静态void main(字符串参数[]){
System.out.printf(“最大的%d、%d和%d是%d\n\n”,
3,4,5,最大值(3,4,5));
System.out.printf(“最大%.1f、%.1f和%.1f为%.1f\n\n”,
6.6,8.8,7.7,最大值(6.6,8.8,7.7));
System.out.printf(“最大%s、%s和%s为%s\n”、“pear”,
“苹果”、“橙色”,最大值(“梨”、“苹果”、“橙色”);
}
}

原语是否可以是可比较的对象?

原语将自动装箱到实现
可比较的包装器对象。

int val=3将成为一个<代码>整数

正式地这是由于您的java编译器需要考虑<强>过载解决> <强>。如果未找到类型的重载,则会考虑加宽类型的重载。如果不存在这样的重载,则会考虑将基元类型自动装箱到相应的装箱类型。使用泛型指定的函数是合适的候选函数

在您的情况下,适当的重载

publicstatict最大值(tx,tyt,tz)

可以找到,编译成功


根据以下条件选择具有此优先级的函数:

  • 类型加宽
  • 自动装箱
  • 可变参数

  • (摘自我的答案)

    就是这里发生的事情-原语
    int
    值被装箱到
    java.lang.Integer
    对象中,并实现
    Comparable
    。自动装箱就是您要寻找的,在原语类型和它们的对应对象之间进行必要的转换(例如
    int
    Integer
    )。这比单纯的自动装箱要复杂一些。这加上重载解析的规则。需要注意的是,
    T
    不能是一个基元类型,它总是一个引用类型。因此,为了能够调用泛型方法,Java必须自动装箱值。在第一个示例中,要
    Double
    在下一步中。