• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Compiler error in case of advanced for-each loop of Map.Entry

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello!
Could anybody explain why the following code is not compile?
------------------------------------------------------------
Map map = new HashMap();
for (Map.Entry e: map.entrySet()){};
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"compiler error: incompatible types
found : java.lang.Object
required: java.util.Map.Entry"
-------------------------------------------------------------
But on the other hand:
-------------------------------------------------------------
Map map = new HashMap();
for (Map.Entry e: (Set<Map.Entry> map.entrySet()){};
-------------------------------------------------------------
and
-------------------------------------------------------------
Map map = new HashMap();
Itarable<Map.Entry> i = map.entrySet();
for (Map.Entry e: i){};
-------------------------------------------------------------
...are compiled well...
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When using raw types, the only thing map.entrySet() can return is a Set of Objects. But you cannot assign an Object to a Map.Entry without a cast. What you can do, however, is:
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic