Java中的整数比较 [英] Integer comparison in Java

查看:165
本文介绍了Java中的整数比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的整数比较很棘手,因为 int Integer 的行为方式不同。我得到那个部分。

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

但是,这个示例程序显示,(整数)400 (第4行)的行为与(整数)5 (第3行)。这是为什么?

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);
    }
}

结果

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


推荐答案

来自 JLS


如果装箱的值为真,则为false,一个字节,或者在\ u0000到\ u007f范围内的字符,或者在-128到127(包括)之间的int或短数字,然后让r1和r2成为p的任意两个装箱转换的结果。总是这样的情况是r1 == r2。

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.

理想情况下,装箱给定的原始值p总会产生相同的参考。实际上,使用现有的实现技术可能不可行。上述规则是务实的妥协。上面的最后一个条款要求将某些常见值装入无法区分的对象中。实现可以懒惰或急切地缓存这些。对于其他值,此公式不允许对程序员的盒装值的身份进行任何假设。这将允许(但不要求)共享部分或全部这些引用。

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.

这可以确保在大多数情况下,行为将是所需的行为,而不会强加不当的性能损失,特别是在小型设备上。例如,较少内存限制的实现可以缓存所有char和short值,以及-32K到+ 32K范围内的int和long值。

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.

这篇关于Java中的整数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆