Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the matter about foreach in java6?

Tags:

java

Map testMap = new HashMap();
for(Map.Entry<String, Object> entry:testMap.entrySet()){

}

it has error tip:"Type mismatch: cannot convert from element type Object to Map.Entry"

Would you tell me the reason?

thanks

like image 892
jimmy Avatar asked Jun 13 '11 07:06

jimmy


4 Answers

testMap is not of generic type, so testMap.entrySet returns objects.

You can correct it like that:

Map<String, Object> testMap = new HashMap<String, Object>();
for(Map.Entry<String, Object> entry:testMap.entrySet()){

}
like image 139
Petar Ivanov Avatar answered Oct 21 '22 01:10

Petar Ivanov


Maybe you should declare testMap as

Map<String, Object> testMap = new HashMap<String, Object>();
like image 35
JeremyP Avatar answered Oct 21 '22 02:10

JeremyP


Your declaration

Map testMap = new HashMap();

does not mention that testMap.entrySet() should be type <String, Object>

The solution is

Map<String, Object> testMap = new HashMap<String, Object>();

No issues with Java6.

like image 3
Sandeep Jindal Avatar answered Oct 21 '22 01:10

Sandeep Jindal


The problem is not with for but with the declaration of your map, you should not use raw types.

Map testMap = new HashMap();

This is more like

Map<Object,Object> testMap = new HashMap<Object,Object>();

and you are trying to cast this to Map.Entry<String, Object>.

The solution for you is to declare properly the object

Map<String,Object> testMap = new HashMap<String,Object>();
like image 1
Damian Leszczyński - Vash Avatar answered Oct 21 '22 02:10

Damian Leszczyński - Vash