0

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.

1
  • Well I did mention "how does these lines work?" and "// Why is this true?" I was pretty specific, maybe I should add that line before that. Commented Nov 17, 2012 at 14:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.