How to remove duplicates from a list using an auxiliary array in Java?

arrays, counter, duplicates, java

Solution

You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.

double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
    tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
    output[i++] = each;
}
System.out.println(Arrays.toString(output));

Problem

I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array. ``` public void removeDuplicates() { double tempa [] = new double [items.length]; int counter = 0; for ( int i = 0; i< numItems ; i++) { for(int j = i + 1; j < numItems; j++) { if(items[i] ==items[j]) { tempa[counter] = j; counter++; } } } double tempb [] = new double [ items.length]; int counter2 = 0; int j =0; for(int i = 0; i < numItems; i++) { if(i != tempa[j]) { tempb[counter2] = items[i]; counter2++; } else { j++; } } items = tempb; numItems = counter2; } ``` and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at ``` tempa[counter] = j; ``` I don't understand how counter could grow to above the value of items.length, where is the logic flaw?

Original source