gpt4 book ai didi

java - ArrayList 值差异

转载 作者:行者123 更新时间:2023-11-30 03:57:32 25 4
gpt4 key购买 nike

我制作了这个程序来接收数字列表作为输入,它需要找到没有配对的数字,并且它在小输入下工作得很好,但是当我给出更大的输入(超过 256)时真的很奇怪。检查每对数字的条件开始说两个相等的数字不相同:/我真的不知道为什么。有人有什么主意吗?

import java.util.Scanner;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
public class HelpRequired{

public static void main(String[] args){

Scanner s = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);

int singleton=0;
int N;

N = s.nextInt();

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

for(int i = 0; i<N; i++){
list.add(s.nextInt());
}

Collections.sort(list);


for(int i = 0;i<list.size();i+=2){
System.out.println("Comparing "+list.get(i)+" with "+list.get(i+1)+" "+(list.get(i)!=list.get(i+1)));
if(list.get(i)!=list.get(i+1)){ /*This starts to say that, for example 128!=128 is true and I have no idea why*/
singleton = list.get(i);
break;
}
}
pw.printf("%d\n",singleton);

pw.flush();





}

}

这是输入文件的片段:

73
73
74
74
75
75
76
76
77
77
78
78
79
79
80
80

这是生成的输出的片段:

Comparing 116 with 116 false
Comparing 117 with 117 false
Comparing 118 with 118 false
Comparing 119 with 119 false
Comparing 120 with 120 false
Comparing 121 with 121 false
Comparing 122 with 122 false
Comparing 123 with 123 false
Comparing 124 with 124 false
Comparing 125 with 125 false
Comparing 126 with 126 false
Comparing 127 with 127 false
Comparing 128 with 128 true

最佳答案

由于您不能在集合中使用原始值(例如 int),Java 会将它们包装在 Integer 对象中。这称为自动装箱:http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

当您比较两个数字时,您使用的是==,因此您正在比较对象标识而不是对象值。在您的示例中,128 的两个值由不同的 Integer 对象表示,因此 == 为 false。

Java 有一个功能,当表示 -127 到 127 范围内的值时,保证获得相同值的相同 Integer 对象。这意味着引用相等将在该范围内起作用,但不一定在该范围之外起作用。

来自language spec :

If the value p being boxed is ... an int between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

要解决您的问题,您应该使用 list.get(i).intValue() = ...list.get(i).equals(...) 相反。

关于java - ArrayList 值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800950/

25 4 0