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 Map
s), 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With