Search code examples
javaarraylistlistiterator

List iterator to add the missing value back to the list


I am trying to insert integer values into a list.Once the values are inserted, I will be checking whether the current and next values have a difference of 10 between each.If yes, I will be adding 10 to the first value and add it back the list.

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());

    }

Two things i can't able to make it work correctly.

Firstly when I am trying to add the difference value back to the list, it is not added to the correct index.For example, the First value is 20 and the second value is 40, the new value 30 is added after 40.

Secondly, the missing value between 70 & 90 which is 80 is not created here.

Kindly correct me on the logic which I am missing here.

thanks for your time.


Solution

  • Javadoc of previousIndex():

    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.)

    It does not, in any way, change the iterator position.

    Use previous() for that:

    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.)