-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
               }

    }
JavaNewbie42
  • 41
  • 1
  • 2
  • 5
  • 7
    Possible duplicate of [Java: Detect duplicates in ArrayList?](http://stackoverflow.com/questions/562894/java-detect-duplicates-in-arraylist) – Jonny Henly Dec 13 '16 at 19:23
  • Possible duplicate of [Finding duplicate values in arraylist](http://stackoverflow.com/questions/7281352/finding-duplicate-values-in-arraylist) – SachinSarawgi Dec 13 '16 at 19:24
  • 1
    Why did you instantiate a new ArrayList in your loop ? you want to check if it has duplicate right? – A Sdi Dec 13 '16 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()` – Jaroslaw Pawlak Dec 13 '16 at 19:39

2 Answers2

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;
}
Steven Waterman
  • 611
  • 4
  • 17
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.

robot_alien
  • 955
  • 2
  • 13
  • 30