Reputation: 778
I was trying on one of the questions on how to find a list of duplicated array.
This program works:
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
}
}
But I have a concept question on the for loop part. If
List<Integer> myObj = new ArrayList<Integer>();
creates an empty arraylist, then how does these lines work?
for(int id : values){ if(myObj.contains(id)){ // Why is this true?
Although documentation says contains
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
But I still don't understand the concept! Thanks in advance for explaining.
Upvotes: 0
Views: 374
Reputation: 4333
You are correct, the first check of myObj.contains(id) will always be false, but see the other part of your code:
else{
System.out.println("not contains "+id);
myObj.add(id);
}
As the loop progresses, your list will be populated - and further iterations may satisfy that condition.
Upvotes: 1