【问题标题】:Java Object <= relational operator checkJava Object <= 关系运算符检查
【发布时间】:2016-08-02 01:57:38
【问题描述】:

在 Java 中,当使用 == 比较两个对象时,它们的引用也会被比较。但是当使用其他关系运算符比较它们时会发生什么?例如:

 Integer a = new Integer(10);
 Integer b = new Integer(9);
 if (a >= b) {
  System.out.println("A is greater");
 }

当我运行它时,我得到输出,因为 A 更大,为什么会这样?参考文献没有被比较还是只是巧合?

另外,如果其中一个参数是原始的,那么非原始参数是否会被展开为原始参数以进行此类比较?

【问题讨论】:

  • 将它输入到源文件中,看看更有趣的类型会发生什么。 一般是语法错误。

标签: java


【解决方案1】:

在您的示例中,Integer(s) 是 unboxed 到原始 int(s)。没有&lt;=(或&gt;=)比较引用类型(没有ComparableComparator或类似的)。

【讨论】:

  • 但是如果不存在运算符重载,它如何拆箱?那是编译器优化吗?
  • 拆箱是一个编译器附加功能,它允许 Java 将包装器类型转换为原始类型(反之亦然)。
【解决方案2】:

除了@Elliott Frisch 的回答,如果对象不能被拆箱(例如BigIntegerBigDecimalString 或任何非数字的实例),compareTo 的 @ 方法使用了 987654326@ 接口,使用关系运算符将结果与0 进行比较:

var a = new BigInteger("10");
var b = new BigInteger("9");
System.out.println(a.compareTo(b) < 0); // prints true, because a < b
System.out.println(a.compareTo(b) > 0); // prints false

比较非数字对象可能很疯狂:

String x = "abcd";
String y = "defg";
System.out.println(x.compareTo(y) < 0); // prints false, because 'a' < 'd'

有了这个,当你需要比较你定义的类时,记得实现Comparable

【讨论】:

    【解决方案3】:

    就像 Elliot Frisch 提到的那样,Integers 已拆箱为 ints。可以将其想象为对象从 Object 转换为基元。

    这是来自您的 Java 的字节码,它表明调用 Integer.intValue 以从 Integer 中取出 int

    # Create Integer
    NEW java/lang/Integer
    DUP
    # Store 10 in the Integer
    BIPUSH 10
    INVOKESPECIAL java/lang/Integer.<init> (I)V 
    ASTORE 1
    
    # Create Integer
    NEW java/lang/Integer
    DUP
    # Store 9 in the Integer
    BIPUSH 9
    INVOKESPECIAL java/lang/Integer.<init> (I)V
    ASTORE 2
    
    # Get Integer(10)
    ALOAD 1
    # Call Integer.intValue (returns int 10)
    INVOKEVIRTUAL java/lang/Integer.intValue ()I
    # Get Integer(9)
    ALOAD 2
    # Call Integer.intValue (returns int 9)
    INVOKEVIRTUAL java/lang/Integer.intValue ()I 
    # Compare 10 < 9
    IF_ICMPLT L3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多