All,
Just a beginner to Programming. I was exploring on the java Collections and Iterator and I would like to know how the cursor is used for iterating the collections.
public class Collections {
public void myFun()
{
int i=0;
List<String> listObj = new ArrayList<String>();
listObj.add("Hello");
Iterator<String> itr = listObj.iterator();
while(itr.hasNext())
{
String s=(String)itr.next();
System.out.println(" List Elements are : " +s);
}
}
public static void main(String[] args) {
Collections collObj = new Collections();
collObj.myFun();
}
}
As per my Understanding, the internal memory representation of listObj variable looks below,
listObj Representation in memory
----------------------------------------
| 45654846 | null | null | .... | null
----------------------------------------
[0] [1] [2] ... [10]
.
/|\
|
|
|
itr (Cursor)
My Question lies in the below line,
while(itr.hasNext())
In Above example, hasNext() returns True. But from my understanding, there is no element in index[1], hence it should return false. But it returns true. please help me to understand this logic.
itr.next() returns the value - "Hello". But as per my understanding, it need to return the next element in the Array List since its already pointing to index[0].
Also, i have viewed the iterator obj in the debugging mode,
NAME VALUE
----- -------
itr ArrayList$Itr (id=45)
|_ cursor 0
|_ expectedModCount 1
|_ lastRet -1
|_ this$0 ArrayList<E> (id=28)
|_ [0] "Hello" (id=40)
- Can you please explain what is lastRet? does it has anywhere related to my Questions?
- Cursors are always pointed to index[0], which means first element in the array List. Please clarify my understanding.
Regards, Cyborgz
I have just debugged the entire code and found below solutions,
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.
itr.next() has below implementations in ArrayList Class,
WRT my program, lastRet = -1 and i = 0; this it will return elementData[0] which is "Hello"
As said by @Eran lastRet is index of last element returned
hasNext()
will return true the first time you call it (before ever callingnext()
), 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 tonext()
:lastRet
is the index of the last element that was returned (by the last call tonext()
):