日期:2014-05-20  浏览次数:20697 次

关于封箱的问题
代码
public   class   Test   {
public   static   void   main(String[]   args){
Integer   a=900;
Integer   b=900;
System.out.println(a==b);
System.out.println(a!=b);
if   (a!=b)   System.out.println( "differrnt   objects ");

}

}
结果
false
true
differrnt   objects

代码
public   class   Test   {
public   static   void   main(String[]   args){
Integer   a=100;
Integer   b=100;
System.out.println(a==b);
System.out.println(a!=b);
if   (a!=b)   System.out.println( "differrnt   objects ");

}

}
结果
true
false

这是什么意思,难道 "== "和 "!= "于数值的大小还有关系   ?

------解决方案--------------------
每种基本类型的包装类都有分界点
可以上sun官方网站上有Java tutorial查
Integer分界点好像是-128到127
Character 是\u0000 - \u007f
Byte和Boolean总是等于
------解决方案--------------------
These special values are the boolean values true and false, all byte values, short and int values between -128 and 127, and any char in the range \u0000 to \u007F

这些值封箱后的对象都是缓存起来了的,所以==将会判断为同一个对象。。。

真是奇怪的语法,不过为了效率也没有办法,所以封箱/拆箱也要用在合适的地方。