Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Artem Danilov
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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...
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • 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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic