What happens in this post?

Map<String, Object> m = new HashMap<String, Object>(); 

Is the Map interface initialized through polymorphism by a descendant class "HashMap"? What is it done for?

  Map<String, Object> m; for (int i = 0; i < aProduct.length; i++) { m = new HashMap<String, Object>(); m.put(ATTRIBUTE_NAME_TEXT, aProduct[i]); m.put(ATTRIBUTE_NAME_PR, aPrice[i]); m.put(ATTRIBUTE_NAME_QT, aQuantity[i]); data.add(m); } 
  • To have a HashMap object, obviously. Ask a question. - rjhdby
  • so why not immediately write HashMap <String, Object> m = new HashMap <String, Object> (); ? Why declare an object type as a Map? - mtb
  • one
    A good approach in Java is programming at the interface level, not implementation - Werder

1 answer 1

There's a meaning. And if in the future you want to use not a HashMap , but another implementation of the Map ? Of course, you can do as you please. And it was done so that you could change the final implementation on the fly (for example, use LinkedHashMap instead of HashMap ).

Therefore, it is customary to operate with interfaces. In order not to bind your code strictly specific implementations.

  • one
    You also need to remember that such a record is often used by "by default", and if you ask why - he will say something like "I don’t even know, I always do that" - rjhdby