Cursor Implementation in Iterator in Java collections

别说谁变了你拦得住时间么 提交于 2019-12-06 11:14:02

hasNext() will return true the first time you call it (before ever calling next()), since the next element is the first element of the list, and your list has a single element.

The first time you call itr.next(), it returns the first element of your list.

cursor is the index of the next element to be returned by a call to next():

/**
 * Index of element to be returned by subsequent call to next.
 */
int cursor = 0;

lastRet is the index of the last element that was returned (by the last call to next()):

/**
 * Index of element returned by most recent call to next or
 * previous.  Reset to -1 if this element is deleted by a call
 * to remove.
 */
int lastRet = -1;

I have just debugged the entire code and found below solutions,

public boolean hasNext() {
            return cursor != size;
        }

This method will return either true or false based on the above logic. the default value of cursor is '0' and its checked against the size of the Array List. i.e., in my case, the hasNext() will return true since Cursor (value=0) != Size ( value=1) and this works well for empty array list as well.

  1. itr.next() has below implementations in ArrayList Class,

    public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }
    

    WRT my program, lastRet = -1 and i = 0; this it will return elementData[0] which is "Hello"

  2. As said by @Eran lastRet is index of last element returned

  3. The Cursor are always set to '0' as its default.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!