我正在尝试解决有关如何查找重复数组列表的问题之一。
该程序的工作原理:
import java.util.*;
public class CheckDuplicates {
public static void main(String[]args){
boolean containsDuplicate;
int[] values = {1,2,3,4,5,6,7,8,9,1,3,4,5,10};
List<Integer> myObj = new ArrayList<Integer>();
Set<Integer> dupInt = new HashSet<Integer>();
for(int id : values){
System.out.println(myObj);
if(myObj.contains(id)){
System.out.println("From contains "+id);
containsDuplicate = true;
dupInt.add(id);
}else{
System.out.println("not contains "+id);
myObj.add(id);
}
}
for(int dup : dupInt)
System.out.println(dup); // prints the duplicates
}
}
但是我有一个关于 for 循环部分的概念问题。如果
List<Integer> myObj = new ArrayList<Integer>();
创建一个空的数组列表,那么这些行是如何工作的?
for(int id : values){ if(myObj.contains(id)){ // Why is this true?
虽然文档说 包含
boolean contains
(Object o) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Specified by: contains in interface Collection
Parameters: o - element whose presence in this list is to be tested
Returns: true if this list contains the specified element
但是我还是不明白这个概念!预先感谢您的解释。
最佳答案
你是对的,myObj.contains(id)的第一次检查总是错误的,但是看看你代码的其他部分:
else{
System.out.println("not contains "+id);
myObj.add(id);
}
随着循环的进行,您的列表将被填充 - 并且进一步的迭代可能会满足该条件。
关于Java使用数组查找重复项(包含概念),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409728/