I am working on an assignment and i have everything working well, I have a list that I have randomly created, and now I have to call a method that removes any duplicated integers in the list. My list size is 100, and when I call my removeDuplicates method it removes most of the duplicates but does not remove all of them. I am wondering if someone can take a look at my method and see why it is doing this. Thanks. Here is my code:
int size = A.size();
for (int i = 0; i < size -1; i++) {
for (int j = i + 1; j < size;) {
if (A.get(i) == A.get(j)) {
A.remove(j);
size--;
}
else
j++;
}
}
Here is my full class:
public class Utility {
public static void selectionSort(List<Integer> A) {
int smIndex, sm;
for (int i = 0; i < A.size(); i++) {
sm = A.get(i);
smIndex = i;
for (int k = i; k < A.size(); k++) {
if (sm > A.get(k)) {
sm = A.get(k);
smIndex = k;
}
}
if (smIndex == i)
;
else {
int temp = A.get(i);
A.set(i, A.get(smIndex));
A.set(smIndex, temp);
}
}
}
public static void removeDuplicates(List<Integer> A) {
/*for (int i = 0; i < A.size() -1; i++) {
for (int j = i + 1; j < A.size();) {
if (A.get(i) == A.get(j)) {
A.remove(j);
}
else
j++;
}
}*/
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < A.size(); j++) {
if (i == j)
;
else if (A.get(i) == A.get(j)) {
A.remove(A.get(j));
j = j-1;
}
else
;
}
}
}
}
This is the test program ( I am just hard coding the 100 for now until i get the remove duplicates figured out):
public class PA1Test extends StopWatch {
public static void main(String[] args) {
int n = 100;
List<Integer> list = new Vector<Integer>();
for (int i = 0; i < n; i++) {
list.add((int) (Math.random()*2*n));
}
start();
selectionSort(list);
stop();
System.out.println("Execution Time: " + getElapsedTime() + " milliseconds");
if (n > 100) {
removeDuplicates(list);
System.out.println(list);
}
else {
System.out.println(list);
removeDuplicates(list);
System.out.println(list);
}
}
}