# ArrayList problem (finding largest no)

• 12-12-2007, 12:26 PM
bugger
ArrayList problem (finding largest no)
I am working on an assignment and I have to find largest number from an ArrayList using Iterator. I wrote following code.

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:
Code:

`102`
Output should be 872. I am not sure what is happening.

Thanks.
• 12-12-2007, 01:33 PM
revathi17
Code:

```import java.util.ArrayList; import java.util.Iterator; public class LargestNumber {         public static void main(String[] args){                 ArrayList<Integer> aList = new ArrayList<Integer>();                 aList.add(101);                 aList.add(872);                 aList.add(777);                 aList.add(102);                 aList.add(23);                                 Iterator<Integer> it = aList.iterator();                 int max = 0;                 while(it.hasNext()){                         int temp = it.next();                         if(temp > max)                                 max = temp;                 }                        System.out.println("Max value:"+max);         } }```
I think what happens is, only if you call it.next() it goes to the next element and continues iteration. This was something new for me too, i just tried giving a temp variable and it worked!!

-R
• 12-12-2007, 01:46 PM
gulapala
Bugger,

When you call it->next, it goes to the next iterator element. So in your code the statement is being called twice due to which, it goes to 3 element, if it satisfies the if condition. So, you should call it only once.
• 12-12-2007, 01:47 PM
bugger
Thanks for the feedback. Yes, its works.
A small thing can make such a big difference :D