有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA:当整数大于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");
}




}
}

共 (3) 个答案

  1. # 1 楼答案

    是的,这是意料之中的。您不应该将对象引用与==!=进行比较。您应该使用.equals(..),或者更好地使用原语int而不是Integer

    问题是,缓存的值最多为128,JVM会给您相同的对象(因此引用比较是有效的)。在128以上,它会创建一个新实例。看看^{}的javadoc(这就是幕后发生的事情)

    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.

  2. # 2 楼答案

    您可以使用整数对象而不是int基元作为变量类型。这将只适用于最大值为128的“=”运算符,因为java缓存它。比较对象的正确方法是。等于()函数

    但请使用原始值

    int i1 = 1;
    int 12 = 2;
    List<Integer> values = ArrayList<Integer>();
    if (!values.contains(i1)) {
     values.add(i); 
    }
    if (!values.contains(i2)) {
     values.add(i2); 
    }
    
  3. # 3 楼答案

    在Java中比较对象时,实际上是在比较引用,而不是在使用==相等运算符时比较值。相反,您应该使用方法.equals()来比较值

    Integer a = 2423;
    Integer b = 5455;
    
    if (a.equals(b)) { ...