2

Here is my code, I wonder how is it possible:

HashMap<Integer,String> hashmap = new HashMap();
hashmap.put(1,"milind");
hashmap.put(2,"nelay");       

HashMap hash = new HashMap();
hash.put("piyush",1);
hashmap.putAll(hash);
for (Object name: hashmap.keySet()) {
   Object key = name.toString();
   Object value = hashmap.get(name);
   System.out.println(key + " " + value);
}

Here is the output:

 1 milind
 2 nelay
 piyush 1
zeroDivider
  • 1,050
  • 13
  • 29
Piyush Sonavale
  • 13
  • 1
  • 1
  • 5

3 Answers3

3

Your hashmap actually did not specify the types for Key/Value, so the Object type (or sub types including Integer, String and whatsoever) is acceptable for both key and value.

Here is your first line:

HashMap hashmap = new HashMap();

If you change this line to:

HashMap<Integer, String> hashmap = new HashMap<Integer, String>();

And continue with the next lines:

HashMap hash = new HashMap();
hash.put("piyush", 1);
hashmap.putAll(hash);

Then it won't compile.

zeroDivider
  • 1,050
  • 13
  • 29
Nguyen Tuan Anh
  • 1,036
  • 8
  • 14
  • After editing the plain markdown, it revealed that the first line was `HashMap hashmap=new HashMap();`. However, it's interesting why it works with the second, un-parameterized map. – Tamas Rev Jun 27 '16 at 06:53
2

Your HashMaps are not typesafe. The following will not compile anymore:

HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "milind");
    hashmap.put(2, "nelay");

    HashMap<String, Integer> hash = new HashMap<String, Integer>();
    hash.put("piyush", 1);
    hashmap.putAll(hash); // will not compile
    for (Object name : hashmap.keySet()) {

        Object key = name.toString();
        Object value = hashmap.get(name);
        System.out.println(key + " " + value);
    }
Christoph Forster
  • 1,728
  • 4
  • 27
  • 39
0

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);
    }
}
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49