This is the second solution to find the sum of integers in an array list with help of normal iterator and list iterator.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class SumarrayList {
public static void main(String[] args) {
List<Integer> arrNums = new ArrayList<Integer>();
int sumNums=0;
//Fill the array list with a few integers
arrNums.add(42);
arrNums.add(521);
arrNums.add(98);
arrNums.add(61);
arrNums.add(3);
arrNums.add(95);
System.out.println( "Using the ListIterator interface traverse through the arrayList");
ListIterator<Integer> liter = arrNums.listIterator();
while (liter.hasNext())
sumNums += liter.next();
System.out.println("The sum of Integers from an arrayList="+sumNums);
sumNums=-0;
System.out.println("Using Iterator interface traverse through the arrayList");
Iterator<Integer> iter = arrNums.iterator();
while (iter.hasNext())
sumNums += iter.next();
System.out.println("The sum of Integers from an arrayList="+sumNums);
}
}
Output:
Using the ListIterator traverse through the arrayList
The sum of Integers from an arrayList=820
Using Iterator interface traverse through the arrayList
The sum of Integers from an arrayList=820

Leave a comment