JAVA:当Integer大于128时比较不起作用
我已经摘录并简化了Java程序的这一部分来进行测试。任务是比较ArrayList中的两个整数并声明它们是否相等。
以下代码适用于数字<128,但任何大于128的数字,该代码将不起作用。
任何帮助都将非常棒,谢谢。
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
。
事实是,最多可缓存128个值,并且JVM为您提供相同的对象(因此引用比较起作用)。在128以上,它将创建一个新实例。查看的javadoc
Integer.valueOf(int)
(这是在幕后发生的)
返回表示指定int值的Integer实例。如果不需要新的Integer实例,则通常应优先于构造方法Integer(int)使用此方法,因为此方法通过缓存经常请求的值可能会产生明显更好的空间和时间性能。
以上是 JAVA:当Integer大于128时比较不起作用 的全部内容, 来源链接: utcz.com/qa/420258.html