猿问

为什么这个 while 循环不会中断?

这是用 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;

    }



慕桂英3389331
浏览 115回答 1
1回答

慕的地6264312

当临时列表中已存在要删除的项目时,您需要更新它们的列表。因此索引列表将包含所有重复元素的索引: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) {&nbsp; //test for duplicates and save their indexes&nbsp; for (int i = 0; i < L.size(); i++) {&nbsp; &nbsp; if (!temp.contains(L.get(i))) {&nbsp; &nbsp; &nbsp; temp.add(L.get(i));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; index.add(i);&nbsp; &nbsp; }&nbsp; }&nbsp; // if there were duplicates they will be removed&nbsp; if (!index.isEmpty()) {&nbsp; &nbsp; stop = 1;&nbsp; &nbsp; for (int j = index.size() - 1; j >= 0; j--) {&nbsp; &nbsp; &nbsp; L.remove((int) index.get(j));&nbsp; &nbsp; }&nbsp; }&nbsp; //if nothing is removed there should be no duplicates and the loop should break&nbsp; if (stop == 0) {&nbsp; &nbsp; break;&nbsp; }&nbsp; index.clear();&nbsp; temp.clear();&nbsp; stop = 0;}
随时随地看视频慕课网APP

相关分类

Java
我要回答