这是我的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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,这是预料之中的.您不应该使用==或比较对象引用!=.您应该使用.equals(..)或更好地使用原语int而不是Integer.
问题是,高达128的值被缓存,JVM为您提供相同的对象(因此参考比较有效).在128以上它创建了一个新实例.看看javadoc Integer.valueOf(int)(这是幕后发生的事情)
返回表示指定int值的Integer实例.如果不需要新的Integer实例,通常应优先使用此方法,而不是构造函数Integer(int),因为此方法可能通过缓存频繁请求的值来显着提高空间和时间性能.
| 归档时间: |
|
| 查看次数: |
3795 次 |
| 最近记录: |