I am working on an assignment and I have to find largest number from an ArrayList using Iterator. I wrote following code.
ArrayList <Integer>alist = new ArrayList<Integer>();
// populating
alist.add(101);
alist.add(777);
alist.add(872);
alist.add(102);
alist.add(23);
// finding the largest number in the ArrayList
Iterator<Integer> it = alist.iterator();
int max = 0;
while(it.hasNext())
{
if( it.next() > max)
max = it.next();
}
System.out.println(max);
It compiles fine but the output is not as required.
Output:
Output should be 872. I am not sure what is happening.
Please look into this.
Thanks.