• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

Set not allowed in enhanced for loop

 
Ranch Hand
Posts: 61
Firefox Browser Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. import java.util.*;
2.class myclass
3.{
4. public static void main(String[] x)
5. {
6. HashMap hm=new HashMap();
7 hm.put("a","b");
8 hm.put("b","b");
9 for(Set s: hm.keySet())
10 {
11 System.out.println(s);
12 }
13 }
14 }

Hello friends here why line 9 generates an error???Can we not use Set in enhanced for loop??if not then why??what are the other classes that are not allowed in enhanced for loop
 
Ranch Hand
Posts: 624
9
BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Abhishek
hashMap.keySet() returns a Set of keys.
So for loop would be like this

It will compile fine.
Note : Please use code tags for java code.
 
Abhishek KumarSoni
Ranch Hand
Posts: 61
Firefox Browser Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks tupus but what is wrong with using Set in for loop
 
Ranch Hand
Posts: 47
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Set is also a collection of elements(Strings in this example). Here, in enhanced for loop, we are specifying the type of each element in that Set..Set itself is not the element.
 
Tapas Chand
Ranch Hand
Posts: 624
9
BSD Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can definitely use Set in enhanced for loop.
You are just using the wrong thing at the wrong place.
hashMap.keySet() returns a Set, out of which you can get only elements of the Set, not another Set.
for your question - "what is wrong with using Set in for loop"...here is a sample for loop with Set for your reference
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic