For example:
ArrayList<Integer> a = new ArrayList<Integer>();
while(a.size() < 50){
a.add(1);
a.add(2);
a.add(9);
}
System.out.println(a);
I would like to remove all the excess 1's, 2's, and 9's, but keep one of each.
Not cleared: [1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9, 1, 2, 9]
Cleared: [1, 2, 9]
Ideally I would like this to work for any x value that occurs any n number of times in the ArrayList.
My partial solution just returns whether or not a value occurs more than once (true if it occurs more than once, false if it doesn't)
public static boolean occ(ArrayList<Integer> l, int s) {
int n = 0;
boolean t = false;
for (int p : l) {
if (p == s) {
n++;
}
}
if (n > 1) {
t = true;
}
return t;
}
Method implementation:
occ(ArrayList, Selected Int Value to be Checked);
If I change to a HashSet or Set, would I be able to implement the ArrayList methods clear()
and size()
?