views:

58

answers:

2

why do i get this exception?

Map myHash = null myHash = (HashMap)Collections.synchronizedMap(new HashMap());

If i try to use this hashmap, i get java.lang.ClassCastException

A: 

Because Collections.synchronizedMap() does not return a HashMap.

Correct way should be:

Map mySyncedMap = Collections.synchronizedMap(new HashMap());

(or any other map instead of HashMap)

A: 

Because Collections.synchronizedMap does not return a HashMap.

It returns some other kind of Map (the type of which you should not need to know), that wraps your HashMap.

You have to use the Map interface instead of HashMap.

Thilo