gpt4 book ai didi

java - If 语句不适用于两个 列表 [Java]

转载 作者:行者123 更新时间:2023-12-01 14:44:19 25 4
gpt4 key购买 nike

long temp;
for ( int i = 0; i < size; i++ )
{
temp = ls.get(i);
System.out.println("temp is:" + temp);
for ( int j = 0; j < size; j++)
{
if ( i == j )
{

}
else if ( ls.get(i) == ls.get(j) )
{
// If Duplicate, do stuff... Dunno what yet.
System.out.println(ls.get(i)+" is the same as: " + ls.get(j) );
//System.out.println("Duplicate");
}

}
}

我有一个 Long 类型的列表,它填充了几个 9 位数字,例如 900876012,我正在检查重复项,以便我可以生成新数字并在导出到文件之前替换重复项。

首先,我检查数组中的位置是否相同,因为显然位置 1 处的某些内容在位置 1 处的同一个列表中将是相同的,如果是,则忽略。

然后,我检查内容是否相同,但由于某种原因它不会被评估为 true,它之前作为一个简单的“if”本身就被评估为 true。

这里是数字供引用,只需忽略“温度是”:

temp is:900876512
temp is:765867999
temp is:465979798
temp is:760098908
temp is:529086890
temp is:765867999
temp is:529086890
temp is:800003243
temp is:200900210
temp is:200900210
temp is:542087665
temp is:900876512
temp is:900876512
temp is:900876512
temp is:900876512

以下是完整的方法供引用:

public static void CheckContents(BufferedReader inFileStreamName, File aFile, Scanner s ) throws DuplicateSerialNumberException
{
System.out.println();
List<Long> ls = new ArrayList<Long>();
List<String> ls2 = new ArrayList<String>();

long SerialNum = 0;
int counter = 0;
int size = 0;
String StringBuffer;

while (s.hasNextLine())
{
ls.add(s.nextLong());
//System.out.println();
StringBuffer = s.nextLine();
ls2.add(StringBuffer);
size = ls.size();
//System.out.println(ls.size());
SerialNum = ls.get(size-1);
//System.out.println(ls.get(size-1));
System.out.println("Serial # is: " + SerialNum);
//System.out.println(SerialNum + ": " + StringBuffer);
counter++;
}

long temp;
for ( int i = 0; i < size; i++ )
{
temp = ls.get(i);
System.out.println("temp is:" + temp);
for ( int j = 0; j < size; j++)
{
if ( i == j )
{

}
else if ( ls.get(i) == ls.get(j) )
{
// If Duplicate, do stuff... Dunno what yet.
System.out.println(ls.get(i)+" is the same as: " + ls.get(j) );
//System.out.println("Duplicate");
}

}
}


}

最佳答案

不错的。

在列表中您不存储float (原始)但是Float对象。自动装箱使您对自己透明。

还有==比较器不适用于对象(它告诉两个对象是否相同,但如果有两个对象持有相同的值,它将返回 false )。

你可以使用

   if ( ls.get(j).equals(ls.get(i)) 

或者(因为它是 List<Long> )

   if ( ls.get(j).longValue() == ls.get(i).longValue())

甚至(感谢自动装箱)

   if ( ls.get(j).longValue() == ls.get(i))

关于java - If 语句不适用于两个 <Long> 列表 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com