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