简体   繁体   English

为什么这个while循环中断?

[英]Why doesn't this while-loop break?

Here's a while-loop written in Java. 这是用Java编写的while循环。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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