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()生成的变量不一样吗?
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()生成的变量不一样吗?
n1==n2比较的是两个对象的reference就像c中指针一样,reference是保存的是它所指向对象的地址,虽然他们指向的对象是“相等”的,可是地址不是相等的要比较对象,可以用n1.equals(n2);
n1==n2比较的是两个对象的reference就像c中指针一样,reference是保存的是它所指向对象的地址,虽然他们指向的对象是“相等”的,可是地址不是相等的要比较对象,可以用n1.equals(n2);
假设这样吧,你们家住东城区5号,我们家住西城区5号,虽然都是5号,但是肯定不是一个地方,也就不一样了
但 Integer n1=new Integer(40);声明的是对象,对象比较时
若用“==”就是比较对象的引用标志,类似与C中的指针地址,
若是用“ni.equals(n2)”才是比较对象表示的值的相等关系。
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.
但 Integer n1=new Integer(40);声明的是对象,对象比较时
若用“==”就是比较对象的引用标志,类似与C中的指针地址,
若是用“ni.equals(n2)”才是比较对象表示的值的相等关系。这个解释我觉的有道理,大家看呢?
难道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 不作为对象处理
只要客户端程序员愿意使用的话是有现成的但是使用简单类型不进方便而且效率高,为什么要取消呢?