0

I always initialize map like Map<String,Object> hsmap = new Hashmap<>() (Assuming hashmap key is a String and value can be any object)

instead of

HashMap <String,Object> hsmap = new Hashmap<>()

As a best practice ,though I'm sure that I will never change this map implementation apart from hashmap for my requirement.

Is ther any other reason to initialize with 1st approach apart from being a best practice to code to interface ?

Siddu
  • 11
  • 2
  • 3
    It's easier to swap implementations. Imagine, you want a `TreeMap` instead. In the first case you just have to change the assignment `Map hsmap = new TreeMap<>()`. With the second approach, you'd also have to change the type `TreeMap hsmap = new Treemap<>()`. – QBrute Jul 01 '17 at 16:40
  • Also see this question: [What does it mean to “program to an interface”?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – d.j.brown Jul 01 '17 at 16:47
  • @QBrute -thanks for the reply - Here in this case - I'm sure I will not change implementation - so I will never change implementation. – Siddu Jul 01 '17 at 16:51
  • Why not switch the question up? What's the advantage of declaring it to be HashMap? It's not so that you can use methods on HashMap that aren't declared in Map, because there aren't any. So you trade something (even if it's something you don't think you'll need, it's still _something_) for nothing. Doesn't seem like a good trade to me. It also makes your code a bit less clear to some people, who might go looking for a reason that you did this non-standard thing (declaring it as HashMap instead of Map). Part of learning a language is learning its idioms. – yshavit Jul 01 '17 at 16:52
  • In some cases - run some tests on interfaces - using the interface type Map instead of the class type HashMap slows access by about 50%. That was a result I had really not anticipated before; but ever since, I try to use the specific class type wherever possible and convenient. Especially interface methods s that only return an interface like Iterable, even though they always return ArrayList, is quite annoying if you want to count the items and so on... – JayC667 Jul 01 '17 at 18:00
  • There's a design paradigm - especially when it comes to co/contravariance, that suggests you make the input to your functions as generic as possible, while the output is as specific as possible. When it comes to interfaces and multilple different implementations of that, it might be wiser to use as generalistic interfaces as possible though. – JayC667 Jul 01 '17 at 18:02

0 Answers0