This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Compiler error in case of advanced for-each loop of Map.Entry Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Compiler error in case of advanced for-each loop of Map.Entry" Watch "Compiler error in case of advanced for-each loop of Map.Entry" New topic
Author

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

Artem Danilov
Greenhorn

Joined: Jan 29, 2006
Posts: 1
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

Joined: Aug 03, 2002
Posts: 7729
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:


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Compiler error in case of advanced for-each loop of Map.Entry