列表迭代器将缺失值添加回列表

List iterator to add the missing value back to the list

我正在尝试将整数值插入 list.Once 值已插入,我将检查当前值和下一个值之间是否相差 10 each.If 是的,我会将 10 添加到第一个值并将其添加回列表。

public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(20);
        arrayList.add(40);
        arrayList.add(50);
        arrayList.add(70);
        arrayList.add(90);

        ListIterator<Integer> iterator = arrayList.listIterator();
        int firstVal = 0;
        int secVal = 0;
        while (iterator.hasNext()) {
            if (iterator.hasPrevious()) {
                firstVal = iterator.previous();
                iterator.next();
            }

            secVal = iterator.next();
            System.out.println("FirstValue " + firstVal);
            System.out.println("secVal " + secVal);
            if (firstVal != 0) {
                if ((secVal - firstVal) > 10) {
                    //iterator.previousIndex();
                    iterator.add(firstVal + 10);
                    firstVal = 0;
                    iterator.next();
                }
            }
        }
        System.out.println("iterator " + iterator.toString());

    }

有两件事我无法使其正常工作。

首先,当我尝试将差异值添加回列表时,它没有添加到正确的 index.For 示例中,第一个值为 20,第二个值为 40,新值 30在40之后添加。

其次,这里没有创建70和90之间的缺失值80。

请纠正我这里缺少的逻辑。

感谢您抽出时间。

问题是当您发现两个元素之间的差异大于 10 并且当您插入时,您调用的不是 iterator.previous();,而是 iterator.previousIndex();

previousIndex() 的 Javadoc:

Returns the index of the element that would be returned by a subsequent call to previous(). (Returns -1 if the list iterator is at the beginning of the list.)

它不会以任何方式改变迭代器的位置。

为此使用 previous()

Returns the previous element in the list and moves the cursor position backwards. This method may be called repeatedly to iterate through the list backwards, or intermixed with calls to next() to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)