JAVA Integer

public class Test {
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
Integer i3 = Integer.valueOf(127);

if (i1 == i2)
System.out.println("i1 == i2 is true!");
else
System.out.println("i1 == i2 is false!");

if (i1 >= i2)
System.out.println("i1 >= i2 is true!");
else
System.out.println("i1 >= i2 is false!");

if (i1 == i3)
System.out.println("i1 == i3 is true!");
else
System.out.println("i1 == i3 is false!");

}
}

当值是127时,输出是:
i1 == i2 is true!
i1 >= i2 is true!
i1 == i3 is true!

当值是128时,输出是:
i1 == i2 is false!
i1 >= i2 is true!
i1 == i3 is false!

说明:
我使用的是Sun JDK 1.5.0_03-b07 和 Eclipse 3.2M4。

“Integer i1 = 127;”在JDK1.4下不能编译通过的,会提示:“ Type mismatch: cannot convert from int to Integer”的错误,一般改写为:“Integer i1 = new Integer(127);”。

“Integer i1 = 127;”在JDK1.5下可以编译通过的,这就是自动装箱(Autoboxing)和自动拆箱(Auto-Unboxing)。自动装箱(Autoboxing)特性让Java自动包装一个简单数据类型(例如int)到对应的包装类型中(例如Integer)中。

在《JSR 201: Extending the Java Programming Language with Enumerations, Autoboxing, Enhanced for loops and Static Import》中,对这个问题,是作了这样的规定:
If the value p being boxed is true, false, a byte, an ASCII character, or an integer or short number between -127 and 128, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

在Java中,The following is the list of primitives stored as immutable objects(不可变对象):
* boolean values true and false
* All byte values
* short values between -128 and 127
* int values between -128 and 127
* char in the range \u0000 to \u007F

为了更容易理解问题,用Jad将上面代码反编译,如下:
import java.io.PrintStream;

public class Test
{

public Test()
{
}

public static void main(String args[])
{
Integer i1 = Integer.valueOf(128);
Integer i2 = Integer.valueOf(128);
Integer i3 = Integer.valueOf(128);

if(i1 == i2)
System.out.println("i1 == i2 is true!");
else
System.out.println("i1 == i2 is false!");

if(i1.intValue() >= i2.intValue())
System.out.println("i1 >= i2 is true!");
else
System.out.println("i1 >= i2 is false!");

if(i1 == i3)
System.out.println("i1 == i3 is true!");
else
System.out.println("i1 == i3 is false!");
}
}

从这可以看出,“Integer i1 = 128;”在JDK1.5下应该编译成了“Integer i1 = Integer.valueOf(128);”。


再看看java.lang.Integer中关于valueOf的源代码是怎样的:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

可以看出,这个值在-128到127之间,会将其cached(缓存)起来,如果多次使用的话,会节省内存和改善性能;如果不在这个范围之内,则生成一个新的Integer Object instance,这样如果进行“==”时,由于是比较两个不同的Object references,故结果是false。事实上,这个特性从JDK 1.3就存在了(以前的我不清楚) 。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值