/**
* Extract unique elements from an array
*
* @param arr input array with redundant elements
*/
public static void removeRedundantElements(ArrayList arr) {
Collections.sort(arr);
// remove the same elements
for (int k = 0; k < arr.size() - 1; k++) {
Object e = arr.get(k);
// try to skip same element
int j = k + 1;
while (j < arr.size()) {
if (arr.get(j).equals(e)) {
arr.remove(j);
j--;
}
j++;
}
}
}
Last edit: Duy Dinh 2013-06-13
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
// temporary array of the same size
int[] b = new int[a.size()];
Collections.sort(a);
// store the first element
b[0] = a.get(0);
int bIndex = 1;
// browse 'a' and collect unique elements into b
// the element collected must not equal to the previous element
for (int aIndex = 1; aIndex < a.size(); aIndex++) {
if (b[bIndex - 1] != a.get(aIndex)) {
b[bIndex] = a.get(aIndex);
bIndex++;
}
}
// copy elements in temporary elements from index 0 to bIndex
int[] result = Arrays.copyOfRange(b, 0, bIndex);
return result;
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Last edit: Duy Dinh 2013-06-13
A better way to get unique elements from an array