Results 1 to 4 of 4
- 12-12-2007, 11:26 AM #1
Senior Member
- Join Date
- Nov 2007
- Posts
- 111
- Rep Power
- 0
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.
It compiles fine but the output is not as required.Java 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);
Output:
Output should be 872. I am not sure what is happening.Java Code:102
Please look into this.
Thanks.
- 12-12-2007, 12:33 PM #2
Member
- Join Date
- Aug 2007
- Posts
- 26
- Rep Power
- 0
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!!Java 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); } }
-R
- 12-12-2007, 12:46 PM #3
Member
- Join Date
- Dec 2007
- Posts
- 11
- Rep Power
- 0
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.Thanks & Regards, G.Rajasekhar
- 12-12-2007, 12:47 PM #4
Senior Member
- Join Date
- Nov 2007
- Posts
- 111
- Rep Power
- 0
Similar Threads
-
Finding Largest Prime Factor
By perito in forum New To JavaReplies: 7Last Post: 11-08-2010, 08:25 PM -
ArrayList problem with images
By Cymro in forum New To JavaReplies: 2Last Post: 02-05-2008, 06:22 PM -
Finding largest and smallest integer
By mlhazan in forum New To JavaReplies: 2Last Post: 01-12-2008, 10:30 PM -
ArrayList problem
By khamuruddeen in forum New To JavaReplies: 7Last Post: 12-22-2007, 05:46 AM -
Finding largest no
By bugger in forum New To JavaReplies: 11Last Post: 11-29-2007, 12:49 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks