2

I am still learning Java, and I am not sure what the difference is in creating these two types of HashMap? Are they the same? If not, is there any major differences?

HashMap<String,String> hash1 = new HashMap <String,String> ();

vs

Map<String,String> myMap = new HashMap<String,String>(); 

I understand the fact that one is calling HashMap type, and the other is calling Map Interface.

P.S - there is one thread that is kind of similar but does not give the exact answer that I am looking for.

Thanks in advance,

Community
  • 1
  • 1
harrisonthu
  • 454
  • 3
  • 7
  • 18
  • 1
    Polymorphism : with your second example, nothing prevents you from reusing the interface for a `TreeMap` for example. There isn't major differences in the fact that the methods are almost all abstractly present within the interface and their implementation are done within the classes. – Yassin Hajaj May 15 '16 at 22:18
  • 1
    Not sure what you are looking for in the answer but this is just a good OO practice. You use interface as reference to a concrete implementation. This forces your code to use simple interface methods without assumption of the actual type. So if in the future if you decide to change HashMap to TreeMap or any other implementation of the Map interface your code will work the same. This is a good practice when designing APIs. – YaRiK May 15 '16 at 22:21
  • @YaRiK Thank you for your explanation. Now, I understand one of the Object Oriented concept. As you mentioned, the second one is better because it would be a lot easier when you decided to change the data structure in the future since you are implementing the Map. Thanks! – harrisonthu May 18 '16 at 02:17

0 Answers0