I have to iterate through an arraylist in this manner.
ArrayList<Integer> li = new ArrayList<Integer>();
li.add(20);
li.add(30);
li.add(40);
li.add(50);
li.add(70);
for (int i = 0; i < li.size() - 1; i++)
System.out.println(li.get(i) + " " + li.get(i + 1));
Output:
20 30
30 40
40 50
50 70
How to do the same using an iterator?
Use two iterators. I tested this and it worked for me.
Edit: No need for inner
if. Silly me.Explanation: the
listIterator(index)method returns an iterator that starts at the specified position in the list where aslistIterator()returns an iterator that starts at position zero.The
firstiterator therefore starts at0and thesecondstarts at1. Then it is merely a question of printing thenext()on both. This will work irrespective of whether the number of elements in the list is odd or even.Edit 2
My logic fu is very weak today. Thanks @barjak for pointing out the case about the empty list and the unnecessary
first.hasNext().