我正在使用 LinkedList 创建一个程序,该程序可以将重复的数字复制到 linkedList 的新实例。
比方说List<Integer> orig = new LinkedList<>()
由这些数字组成:23,1000,1000,1,23
我想将重复的数字复制到 List<Integer> copy = new LinkedList<>()
应该是 23 和 1000,因为我有 2 个重复的数字。我尝试在数组中测试它并且它有效。但不知道为什么它在 LinkedList 中不起作用。
List<Integer> list1 = new LinkedList<>();
list1.add(23);
list1.add(1000);
list1.add(1000);
list1.add(1);
list1.add(23);
List<Integer> list2 = new LinkedList<>();
for(int x = 0; x <= list1.size()-1; x++) {
for(int y = x+1; y <= list1.size()-1; y++) {
if(list1.get(x)==list1.get(y)) {
list2.add(list1.get(x));
}
}
}
for(int y = 0; y <= list2.size()-1; y++) {
System.out.println(list2.get(y));
}
- 当前输出:
23
- 预期输出为:
23,1000
最佳答案
要向现有答案添加解释:
在 Java 中,有两种比较事物的方法 - ==
和 equals
,其中后者用于比较对象(简短版本) ,详情参见 What is the difference between == and equals() in Java? )。因此,比较两个 Integer 的正确方法确实是 x.equals(y)。
输出仍然包含“23”的原因是 Java 的整数缓存。 Java specification明确要求对于 -127 到 +128 之间的所有数字,x == y
为 true(也是简短版本,有关详细信息,请参阅
Integers caching in Java)。
简短演示:
Integer a1 = 23;
Integer a2 = 23;
Integer b1 = 1000;
Integer b2 = 1000;
System.out.println(a1 == a2); // true
System.out.println(a1.equals(a2)); // true
System.out.println(b1 == b2); // false
System.out.println(b1.equals(b2)); // true
关于java - LinkedList 无法复制某些重复的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738788/