listiterator add method issue
How does list iterator add method work? Using the code below why doesn't the string "TREEEEEEEEEEEES" get printed when I execute the"List Iterator forward" loop?
public class PracticeClass5
{
@Test
public void LearningXMLSuite()
// Method 1
List<String> myarraylist1 = new ArrayList<String>();
myarraylist1.add("Oranges");
myarraylist1.add("Apples");
myarraylist1.add("Strawberries");
myarraylist1.add("Watermelon");
myarraylist1.add("Cantalope");
myarraylist1.add("Berries");
myarraylist1.add(6, "banannas");
for (int i=0; i< myarraylist1.size(); i++)
{
System.out.println("Fruits " + i +" = " +myarraylist1.get(i));
}
System.out.println();
ListIterator<String> myitr1 = myarraylist1.listIterator();
myitr1.add("TREEEEEEEEEEEES");
for (int i=0; i< myarraylist1.size(); i++)
{
System.out.println("After adding " + i +" = " +myarraylist1.get(i));
}
System.out.println();
/// does not work
while (myitr1.hasNext())
{
System.out.println("List Iterator forward " +myitr1.next());
}
System.out.println();
while (myitr1.hasPrevious())
{
System.out.println("List Iterator backward " +myitr1.previous());
}
System.out.println();
}
}
**Output**
Fruits 0 = Oranges
Fruits 1 = Apples
Fruits 2 = Strawberries
Fruits 3 = Watermelon
Fruits 4 = Cantaloupe
Fruits 5 = Berries
Fruits 6 = bananas
After adding 0 = TREEEEEEEEEEEES
After adding 1 = Oranges
After adding 2 = Apples
After adding 3 = Strawberries
After adding 4 = Watermelon
After adding 5 = Cantalope
After adding 6 = Berries
After adding 7 = bananas
List Iterator forward Oranges
List Iterator forward Apples
List Iterator forward Strawberries
List Iterator forward Watermelon
List Iterator forward Cantaloupe
List Iterator forward Berries
List Iterator forward bananas
List Iterator backward bananas
List Iterator backward Berries
List Iterator backward Cantaloupe
List Iterator backward Watermelon
List Iterator backward Strawberries
List Iterator backward Apples
List Iterator backward Oranges
List Iterator backward TREEEEEEEEEEEES
Solution 1:
Because iterator does not move forward when you add an element. You have a list:
"Oranges" "Apples" "Strawberries" ...
When you call myarraylist1.listIterator()
the Iterator gets created, and it's 'current' (cursor) position is set to be just before "Oranges"
, like that:
"Oranges" "Apples" "Strawberries" ...
//Iterator points here ^
Then you add an item to the front with myitr1.add("TREEEEEEEEEEEES")
, but the iterator's cursor does not move, so it looks like that:
"TREEEEEEEEEEEES" "Oranges" "Apples" "Strawberries" ...
//Iterator points here ^
If you call myitr1.previous()
before your while (myitr1.hasNext())
loop, it will go one element back, and point to the place you want.