The generic type parameters, like <Integer, String>
add some compile-time checking. Otherwise, the HashMap can contain anything.
Since the second map, HashMap hash=new HashMap();
has no type parameters, it passes the compiler check for void putAll(Map<? extends K,? extends V> m)
. Then, it can work well on runtime.
However, the caller of the map will have a very difficult task to deal with Objects of unexpected type. This is how you can fix it on compiler level:
private static void foo() {
HashMap<Integer,String> hashmap=new HashMap<>(); // diamond syntax to specify right-hand type
hashmap.put(1,"milind");
hashmap.put(2,"nelay");
HashMap<String, Integer> hash=new HashMap<>(); // diamond syntax again
hash.put("piyush",1);
hashmap.putAll(hash); // compile error
for (Object name: hashmap.keySet())
{
Object key =name.toString();
Object value = hashmap.get(name);
System.out.println(key + " " + value);
}
}