简体   繁体   中英

Why doesn't this while-loop break?

Here's a while-loop written in Java. The purpose is to remove all the duplicates from the list. But the loop is not breaking. There might be other mistakes too.

public static <E extends Comparable<? super E>> void removeDuplicates(ArrayList<E> L) {
    ArrayList<E> temp = new ArrayList<E>(L.size());
    ArrayList<Integer> index = new ArrayList<>(L.size());
    int stop = 0;

    while (true) {
        //test for duplicates and save their indexes
        for (int i = 0; i < L.size(); i++) {
            if (!temp.contains(L.get(i))) {
                temp.add(L.get(i));
                index.add(i);
            }
        }
        // if there were duplicates they will be removed
        if (!index.isEmpty()) {
            stop = 1;
            for (int j = 0; j < index.size(); j++) {
                L.remove(index.get(j));
            }
        }
        //if nothing is removed there should be no duplicates and the loop should break
        if (stop == 0) {
            break;
        }
        index.clear();
        temp.clear();
        stop = 0;
    }

} 

You need to update the list of items to be removed when they are already present in the temp list. So the index list will contains index of all duplicate elements:

public static <E extends Comparable<? super E>> void removeDuplicates(final ArrayList<E> L) {
final ArrayList<E> temp = new ArrayList<E>(L.size());
final ArrayList<Integer> index = new ArrayList<>(L.size());
int stop = 0;

while (true) {
  //test for duplicates and save their indexes
  for (int i = 0; i < L.size(); i++) {
    if (!temp.contains(L.get(i))) {
      temp.add(L.get(i));
    } else {

      index.add(i);
    }
  }
  // if there were duplicates they will be removed
  if (!index.isEmpty()) {
    stop = 1;
    for (int j = index.size() - 1; j >= 0; j--) {
      L.remove((int) index.get(j));
    }
  }
  //if nothing is removed there should be no duplicates and the loop should break
  if (stop == 0) {
    break;
  }
  index.clear();
  temp.clear();
  stop = 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM