-1

I'm not sure how I should check for duplicates in my arrayList. I want to return true or false in my output depending on whether or not the array contains duplicate numbers. The numbers are being pulled from another class.

public class Data {

    private ArrayList<Double> sets;

    public Data(double[] set) {
        this.sets = new ArrayList<Double>();
        for (double i : set) {
            this.sets.add(i);
        }
    }       
    public double hasDuplicate(){
        for (int i = 0; i < 6; i++) {
               ArrayList<Double> sets = new ArrayList<Double>();
               for (int j = 0; j < 6; j++)
                sets.add(); //confused with this
               }

    }
4
  • 7
    Possible duplicate of Java: Detect duplicates in ArrayList? Commented Dec 13, 2016 at 19:23
  • Possible duplicate of Finding duplicate values in arraylist Commented Dec 13, 2016 at 19:24
  • 1
    Why did you instantiate a new ArrayList in your loop ? you want to check if it has duplicate right? Commented Dec 13, 2016 at 19:25
  • 1
    Why your hasDuplicate method returns double and not boolean? Why are you iterating up to 6 only? You could just throw in your numbers into the set and then check whether size of the set is same as size of the list: return new HashSet(sets).size() != sets.size() Commented Dec 13, 2016 at 19:39

2 Answers 2

1

Iterate over the elements, keeping track of which you've seen. If you see one you've already seen, you can return true.

public boolean hasDuplicate(){
    Set<Double> seenValues = new HashSet();
    for(Double value : sets){
        if(seenValues.contains(value){
            return true;
        }
        else{
            seenValues.add(value);
        }
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are creating a new Arraylist of sets 6 times in your code. Which is unnecessarily a waste. Initialize it once. Keep adding values to it in the for loop. Also use List sets = new ArrayList(); By this it becomes implementation independent. Like in future you could use LinkedList(); for the same without much change.

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.