int a = 128;
Integer b = 128;
Integer c = 128;
Integer d = new Integer(128);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false
falseint a = 12;
Integer b = 12;
Integer c = 12;
Integer d = new Integer(12);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false谁能解释下为什么有这样的结果?
Integer b = 128;
Integer c = 128;
Integer d = new Integer(128);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false
falseint a = 12;
Integer b = 12;
Integer c = 12;
Integer d = new Integer(12);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c);
System.out.println(b==d);
System.out.println(c==d);
答案:
true
true
true
true
false
false谁能解释下为什么有这样的结果?
解决方案 »
- thinking in java上关于IO的题目
- 请教:java中显示二进制的问题
- 想写一个查找局域网内所有QQ号的软件,用java如何来写,还请高手指点一二!
- 各位大哥救命啊..........
- applet如何取一张图片的原始的高和宽.因为我要在显示的时候给它放大一倍
- ie如何修复:Microsoft Internet Explorer 遇到问题需要关闭。我们对此引起的不便表示抱歉。
- ◆◆◆一个线程的问题,请高手指点!◆◆◆
- jbuilder8->Tools->configure libraries是配置什么的?
- 请JAVA高手指点:JAVA初学者应该看什么书,和JAVA的学习路线?有高分,QQ:4931851急!!急!!急!!!
- 弱弱的问:把classpath设置成这样是什么意思?在线等待
- 高手们过来集合,准备接分!
- java 中怎么添加一个圆形的按钮
new出来的对象不是放在堆中么,为什么会与int的地址相同,
最不明白就是2个new出的Integer 与int相等,而这两个Integer却不相等。
谁能告诉我具体是怎么样的
比如 int == Integer 系统会自动取Integer类型的int值来和前面的int比较
当 Integer == int 时,系统将自动将int类型包装成Integer对象来比较地址
这时我的理解.....
当Integer小于128时使用的Integer是常量,只有当包装的int值大于等于128时系统才分配新的对象
这时java的性能优化。
其它包装类也类似
栈 堆 池
找一些资料看看,<<java核心技术>>有详细的说明,看一下吧
Integer b = 128;
Integer c = 128;
Integer d = new Integer(128);
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a==d);
System.out.println(b==c); //这里是false
System.out.println(b==d);
System.out.println(c==d);
还有一点比较有意思,<Java Puzzlers>一书里的一个例子:
请提供i1和i2的声明,(i1!=i2)&&(i1<=i2)&&(i1>=i2)为true。
看到i1<=i2 并且i1>=i2都成立,我们自然的想法就是i1==i2,但是java中的autoboxing和auto-unboxing破坏了这点。
看这个声明:
Integer i1=new Integer(0);
Integer i2=new Integer(0);
那么i1>=i2和i1<=i2都是true,因为使用>=和<=的时候会进行auto-unboxing操作,实际比较的是i1和i2auto-unboxing之后的基本类型值,因此这两个都是true,而i1和i2明显指向的不是同一个对象,所以i1!=i2也是true。这个很有意思