JAVA:当Integer大于128时,比较不起作用 [英] JAVA: Comparison not working when Integer larger than 128

查看:1886
本文介绍了JAVA:当Integer大于128时,比较不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Java程序的一部分,我已经拿出并简化为测试。任务是比较ArrayList中的两个整数并说明它们是否相等。

This a section of my Java program I've taken out and simplified to test. The task is to compare two integers from an ArrayList and state whether they are equal.

以下代码适用于数字<128但任何数字> 128且代码将不行。

The below code works for numbers <128 but any number >128 and the code will not work.

任何帮助都会非常棒,
谢谢。

Any help would be really great, thanks.

import java.util.*;

public class test
{
public static void main (String[] args)
{

Integer seat1Store = 128;
Integer seat2Store = 128;
Integer seat3Store = 0;
Integer seat4Store = 0;
Integer seat5Store = 0;


ArrayList<Integer> proceedArray = new ArrayList<Integer>();


if (seat1Store !=0)
{
    proceedArray.add(seat1Store);
}
if (seat2Store !=0)
{
    proceedArray.add(seat2Store);
}
if (seat3Store !=0)
{
    proceedArray.add(seat3Store);
}
if (seat4Store !=0)
{
    proceedArray.add(seat4Store);
}
if (seat5Store !=0)
{
    proceedArray.add(seat5Store);
}

System.out.println("ArrayList = " + proceedArray);


boolean proceed = false;


for(int i = 0; i<proceedArray.size();i++)
{
    for(int p=0; p<proceedArray.size(); p++)
    {
        if(i != p)
        {
            if(proceedArray.get(i) == proceedArray.get(p))
            {
                System.out.println("DUPLICATE");
                System.exit(0);
            }
        }
    }
    proceed = true;
}


if (proceed == true)
{
    System.out.println("PROCEEDED");
}




}
}


推荐答案

是的,这是预期的。您不应该将对象引用与 == != 进行比较。您应该使用 .equals(..)代替或更好 - 使用原始 int 而不是 Integer

Yes, that's expected. You should not compare object references with == or !=. You should use .equals(..) instead, or better - use the primitive int rather than Integer.

事实是,高达128的值被缓存,JVM为您提供相同的对象(因此参考比较作品)。在128以上它创建了一个新实例。查看 <$的javadoc c $ c> Integer.valueOf(int) (这是幕后发生的事情)

The thing is, values up to 128 are cached, and the JVM gives you the same objects (hence the reference comparison works). Above 128 it creates a new instance. Look at the javadoc of Integer.valueOf(int) (which is what happens behind the scene)


返回表示指定int值的Integer实例。如果不需要新的Integer实例,通常应优先使用此方法,而不是构造函数Integer(int),因为此方法可能通过缓存频繁请求的值来显着提高空间和时间性能。

Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

这篇关于JAVA:当Integer大于128时,比较不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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