I was experimenting with various ways of instantiating a HashMap and there's a problem I've been facing. One would be able to choose between the following, when creating a map from String to String:
Map<String, String> map = new HashMap<String, String>();
Map<String, String> map = new HashMap<>();
Map<String, String> map = new HashMap();
The benefit of using the first one, I thought, would be to bind the overall object in memory to the String type for both key and value, since the reference(map) would point to the actual object of type HashMap<String, String>
Running the following code throws no error and displays reasonable output:
Map<String, String> map = new HashMap<String, String>();
map.put("hi", "there");
Map map2 = map;
map2.put(5, 4);
System.out.println(map.get("hi"));
System.out.println(map2.get("hi"));
System.out.println(map2.get(5));
System.out.println(map2.get(5).getClass());
System.out.println(map.size());
the output is:
there
there
4
class java.lang.Integer
2
We can clearly see that both references point to the same object in memory, which I thought would be of type HashMap<String, String>, but we can add any subtype of Object, when the reference is not parameterized.
My question is, since the parameterized constructor does not matter for the object stored in memory, why would we ever want to repeat the types on the right side? Why write this:
Map<String, String> map = new HashMap<String, String>();
instad of this:
Map<String, String> map = new HashMap();
even if it has the same effect?