I have found something interesting to happen with Maps, rawtypes and generics. Following code:
static {
Map map = new HashMap ();
Set &l
I think the short answer is that Java allows "unchecked cast" in some situations but not others. Dealing with raw types (Generic types without a specified type) is one of these instances.
Keep in mind that for (Map.Entry entry : set) is equivalent to:
Iterator it = set.iterator();
while (it.hasNext())
{
Map.Entry entry = it.next();
}
The assignment:
Set set = map.entrySet();
is allowed and will not generate any warning, as you are not introducing any new type, but in the for loop it.next() will return type Object and you will get compiler exception if you assign it without an explicit cast.
The assignment:
Set set = map.entrySet();
is allowed but will generate an "unchecked cast" warning because of the explicit type Map.Entry and in the for loop it.next() will return type Map.Entry and the assignment will work fine.
You can put the explicit cast in the for loop like this:
for(Map.Entry entry : (Set) map.entrySet())