仅在放入变量时才等于

时间:2014-04-23 01:43:01

标签: java equals

我有两个要比较的值。当使用==运算符直接比较时,它们似乎不相等,但在将它们放入局部变量后相等。谁能告诉我为什么?

代码如下:

(MgrBean.getByName(name1).getId() == MgrBean.getByName(name2).getId()),
//This one is false,

int a = MgrBean.getByName(name1).getId();
int b = MgrBean.getByName(name2).getId();
(a == b); //This one is true.

2 个答案:

答案 0 :(得分:-1)

我相信您的getId()正在返回Integer而不是int

Integerint基元类型的包装类。如果使用==比较对象引用,则比较它们是否引用相同的对象,而不是比较内部的值。因此,如果您要比较两个Integer对象引用,则不是要比较它的整数值,而只是检查这两个引用是否指向同一个Integer对象。

但是,如果使用基本类型来存储该值(例如int a = ....getId()),则会发生自动取消装箱,并且该包装器对象将转换为基本类型值,并使用{{比较基元类型值1}}正在比较价值,这是你期望的工作。

建议您继续阅读:

  1. Java中的原始类型与引用类型
  2. Java中的自动装箱和拆箱

答案 1 :(得分:-1)

The most misconception about Integer type happens everywhere including other answers here

假设您有两个如下定义的整数:

Integer i1 = 128
Integer i2 = 128

If you then execute the test (i1 == i2), the returned result is false. The reason is that the JVM maintains a pool of Integer values (similar to the one it maintains for Strings). But the pool contains only integers from -128 to 127. Creating any Integer in that range results in Java assigning those Integers from the pool, so the equivalency test works. However, for values greater than 127 and less than -128), the pool does not come into play, so the two assignments create different objects, which then fail the equivalency test and return false.

如果是,请考虑以下任务:

Integer i1 = new Integer(1); // Any number in the Integer pool range
Integer i2 = new Integer(1); // Any number in the Integer pool range

因为这些作业是使用' new'关键字,它们是创建的新实例,而不是从池中获取的。因此,对前面的赋值进行测试(i1 == i2)将返回false。

这里有一些说明整数池的代码:

public class IntegerPoolTest {
    public static void main(String args[]){
        Integer i1 = 100;
        Integer i2 = 100;
        // Comparison of integers from the pool - returns true.
        compareInts(i1, i2); 

        Integer i3 = 130;
        Integer i4 = 130;
        // Same comparison, but from outside the pool 
        // (not in the range -128 to 127)
        // resulting in false.
        compareInts(i3, i4); 

        Integer i5 = new Integer(100);
        Integer i6 = new Integer(100);
        // Comparison of Integers created using the 'new' keyword 
        // results in new instances and '==' comparison leads to false.
        compareInts(i5, i6); 

    }

    private static void compareInts(Integer i1, Integer i2){
        System.out.println("Comparing Integers " + 
           i1 + "," + i2 + " results in: " + (i1 == i2) );
    }
}