java整数比较,Java中的整数比较

本文解析了Java中Integer类型隐式转换的微妙差异,探讨了为什么(Integer)400和(Integer)5的行为不一致。通过JLS规则,我们了解到这种行为背后的原理,涉及 Boxing 和 Caching。
摘要由CSDN通过智能技术生成

Integer comparison in Java is tricky, in that int and Integer behave differently. I get that part.

But, as this example program shows, (Integer)400 (line #4) behaves differently than (Integer)5 (line #3). Why is this??

import java.util.*;

import java.lang.*;

import java.io.*;

class Ideone

{

public static void main (String[] args) throws java.lang.Exception

{

System.out.format("1. 5 == 5 : %b\n", 5 == 5);

System.out.format("2. (int)5 == (int)5 : %b\n", (int)5 == (int)5);

System.out.format("3. (Integer)5 == (Integer)5 : %b\n", (Integer)5 == (Integer)5);

System.out.format("4. (Integer)400 == (Integer)400 : %b\n", (Integer)400 == (Integer)400);

System.out.format("5. new Integer(5) == (Integer)5 : %b\n", new Integer(5) == (Integer)5);

}

}

Result

1. 5 == 5 : true // Expected

2. (int)5 == (int)5 : true // Expected

3. (Integer)5 == (Integer)5 : true // Expected

4. (Integer)400 == (Integer)400 : false // WHAT?

5. new Integer(5) == (Integer)5 : false // Odd, but expected

解决方案

From the JLS

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值