为什么这个while循环中断?

时间:2019-09-14 18:10:24

标签: java arrays 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;
    }

} 

1 个答案:

答案 0 :(得分:1)

当临时列表中已经存在要删除的项目时,您需要对其进行更新。因此,索引列表将包含所有重复元素的索引:

accept