簡體   English   中英

為什么這個while循環中斷?

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

這是用Java編寫的while循環。 目的是從列表中刪除所有重復項。 但是循環並沒有中斷。 可能還會有其他錯誤。

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;
    }

} 

如果臨時列表中已經存在要刪除的項目,則需要對其進行更新。 因此,索引列表將包含所有重復元素的索引:

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