java.util.Map key:public static void unnecessaryCast() {
Map map = new HashMap();
map.put("language", "Java");
for(Iterator it = map.keySet().iterator(); it.hasNext();) {
//casting key to String is unnecessary for map lookup
String key = (String) it.next();
//casting to String is unnecessary for println
String val = (String) map.get(key);
System.out.println("key = " + key + ", value = " + val);
}
}Casting (in red) for the map key is not needed for the purpose of calling java.util.Map.get(key), unless you also need a String type of key later.Casting (in blue) for the map value is not needed for the purpose of
System.out.println(value), unless you also need a String type of value later. JVM will correctly dispatch to String.toString() when you concatenate ", value = " to an java.lang.Object value.So I would simply change the two lines to:
Object key = it.next();
Object val = map.get(key);