【问题标题】:Is primitive int also a Comparable?原始 int 也是 Comparable 吗?
【发布时间】:2017-01-19 16:28:45
【问题描述】:

我刚刚看到一个 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"));
   }
}

原语可以以某种方式成为 Comparable 对象吗?

【问题讨论】:

  • Autoboxing 是这里发生的事情 - 原始的 int 值被装箱到 java.lang.Integer 对象中,并且实现了 Comparable&lt;Integer&gt;
  • 自动装箱是您正在寻找的,在必要时在原始类型及其对应对象之间进行转换(例如int Integer)。
  • 它比单纯的自动装箱要复杂一些。就是这样加上重载决议的规则。
  • 需要注意的是T不能是原始类型,它始终是引用类型。因此,为了能够调用泛型方法,Java 必须将值装箱,这会自动发生。在第一个示例中为Integer,在下一个示例中为Double

标签: java generics


【解决方案1】:

原语将自动装箱为实现Comparable 的包装器对象。 int val = 3; 将变成 Integer autoboxing and unboxing java

【讨论】:

    【解决方案2】:

    正式地说,这是由于您的 Java 编译器需要考虑重载分辨率。如果未找到您的类型的重载,则会考虑加宽类型的重载。如果不存在这样的重载,那么会考虑将您的原始类型 自动装箱 到相应的装箱类型。用泛型指定的函数合适的候选者。

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

    public static &lt;T extends Comparable&lt;T&gt;&gt; T maximum(T x, T y, T z)

    可以找到,编译成功。


    根据JLS 15.12.2选择具有此优先级的函数:

    1. 类型加宽
    2. 自动装箱
    3. 变量参数

    (摘自我的回答Why is f(Double x) a better match than f(double... x)?

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多