Forums Register Login

output java.util.Set element using regular for loop

+Pie Number of slices to send: Send
Hello I have a questions regarding output with Set interface: given Set setA of type Integer we can do using for-each loop:
for(Object obj : setA){
Integer intgr = (Integer) obj;
System.out.println(intgr);
}

Now what's the above using the regular for loop
for(int i=0; i < setA.size(); i++){
Integer intgr = (Integer) setA.iterator().next(); //this is the problem
System.out.println(intgr);
}
Eg setA elements in random order may be [88,40,55,12]

For me using the regular for loop will output the first element setA.size() times instead of the iterating to the next element.

My output 12 12 12 12 instead of say 12 40 55 88

Any ideas? Thanks.
+Pie Number of slices to send: Send
You can't index a set with an integer index; you have to actually use the Iterator for the loop, like this:



But the new for-loop is neater -- and check out "generics" when you have a chance, because then you can reduce this to

+Pie Number of slices to send: Send
Its nothing to do with the type of loop you are using. Think about what:

does. It returns an iterator to iterate over the contents of the set. Now calling that inside your loop is analagous to writing:

Can you see what is wrong with that?
[ June 13, 2008: Message edited by: Paul Sturrock ]
+Pie Number of slices to send: Send
In fact I tried the setA.iterator().hasNext() approach and it gives the same output.

I know if I use a "while" the hasNext() approach will definitely work. Using for wouldn't because hasNext returns a boolean (which while loop checks) but for loop don't use boolean but indexing. So if I do next(), I suspect it doesn't go to the "next" item.

However, I expect if I explicitly increment the index inside the for loop it should work.
+Pie Number of slices to send: Send
 

Originally posted by K. Tsang:
In fact I tried the setA.iterator().hasNext() approach and it gives the same output.



Take care that you only create one iterator before the loop starts.

Ernest has already provided an example that does that.

Using for wouldn't because hasNext returns a boolean (which while loop checks) but for loop don't use boolean but indexing.



No, a for loop works in a much more general way. It's perfectly legal to write, for example

passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 17611 times.
Similar Threads
question about == in wrappers
how to compare elements of List
Array conversion Question from Dan's test
Java ---== operato
alert() is changing script function
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:15:07.