• Post Reply Bookmark Topic Watch Topic
  • New Topic

output java.util.Set element using regular for loop  RSS feed

 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!