Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the variable declared as Map and initialized as HashMap; aren't they different types? [duplicate]

Let's say I want to make a HashMap of grades.

 Map<String,Integer> grades = new HashMap<String,Integer>(); 
 grades.put("John", 87); // this work due to auto-boxing right?
 grades.put("Luke", Integer(85)); // non-autoboxed, is this redundant? 

Why is Map on the left and HashMap<K, V>( ); on the right? Isn't it pretty much a rule that you need type consistency whenever you create an object? Unless the static type of names is Map and the dynamic type is HashMap, which presumably is a subclass of Map. But why would you want to do this? Method calls are called from the perspective of an objects static type (e.g Maps), but if there are overridden methods in the dynamic type, those methods will be called. Is this why the types are different?

Thanks! Newbie question but this stuff can be confusing...

EDIT:

Thanks! So the general format is: Interface varName = new ImplementedClassConstructor(); ? And we often choose a superclass Interface because it allows easier substitution later (e.g. if I wanted to change HashMap to TreeMap?

like image 420
bambo222 Avatar asked Mar 21 '23 15:03

bambo222


1 Answers

This is called "programming to an interface" - a rather common and very useful practice.

Map<String,Integer> is an interface. It cannot be instantiated. Variables of interface types need to be assigned objects of classes that implement these interfaces.

HashMap<String,Integer> is a class that implements Map<String,Integer>, so the assignment is valid. If you decide to change the type later, and use TreeMap<String,Integer> instead of HashMap<String,Integer>, all you need to do is change the type in the new expression. The rest of your code would remain the same.

like image 51
Sergey Kalinichenko Avatar answered Apr 23 '23 01:04

Sergey Kalinichenko