int i = 40;
int j = 40;
if(i==j)
{ System.out.println("i==j is true!");   }
else
{ System.out.println("i==j is false!");  }
 
Integer n1 = new Integer(40);
Integer n2 = new Integer(40);
System.out.println("n1 == n2 is "+(n1 == n2));
System.out.println("n1 != n2 is "+(n1 != n2));运行结果显示:
i==j is true!
n1 == n2 is false
n1 != n2 is true
我知道n1,n2比较的是对象,但同理i==j比较的也应该是对象阿!
难道int 定义的变量和 new Integer()生成的变量不一样吗?

解决方案 »

  1.   

    i==j比较的是两个变量
    n1==n2比较的是两个对象的reference就像c中指针一样,reference是保存的是它所指向对象的地址,虽然他们指向的对象是“相等”的,可是地址不是相等的要比较对象,可以用n1.equals(n2);
      

  2.   

    i==j比较的是两个变量
    n1==n2比较的是两个对象的reference就像c中指针一样,reference是保存的是它所指向对象的地址,虽然他们指向的对象是“相等”的,可是地址不是相等的要比较对象,可以用n1.equals(n2);
      

  3.   

    new 以后对象的存储地址就不一样了,==比的是相应地址的值
    假设这样吧,你们家住东城区5号,我们家住西城区5号,虽然都是5号,但是肯定不是一个地方,也就不一样了
      

  4.   

    int 声明的是简单数据类型,所以比较其值相等与否时可以用“==”
    但 Integer n1=new Integer(40);声明的是对象,对象比较时
      若用“==”就是比较对象的引用标志,类似与C中的指针地址,
      若是用“ni.equals(n2)”才是比较对象表示的值的相等关系。
      

  5.   

    我还是不明白,int i = 40; 和 Integer i = new Integer(40);不同吗?
      

  6.   

    int是“primitive type”,Interger 才是“class”看API文档里是这么说的:
    The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
      

  7.   

    int 声明的是简单数据类型,所以比较其值相等与否时可以用“==”
    但 Integer n1=new Integer(40);声明的是对象,对象比较时
      若用“==”就是比较对象的引用标志,类似与C中的指针地址,
      若是用“ni.equals(n2)”才是比较对象表示的值的相等关系。这个解释我觉的有道理,大家看呢?
      

  8.   

    比较对象值用n1.equals(n2)我知道n1,n2比较的是对象,但同理i==j比较的也应该是对象阿!
    难道int 定义的变量和 new Integer()生成的变量不一样吗?
    ========================================肯定不一样!The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.可见,i,j 不作为对象处理
      

  9.   

    这是有点象是JAVA的BUG.即使它是完全面向对象的,那么应该把 int i float j 也定义成对象而完全取消基本类型的概念.
      

  10.   

    所有的简单类型java都封装成对象的
    只要客户端程序员愿意使用的话是有现成的但是使用简单类型不进方便而且效率高,为什么要取消呢?