but declaring a HashMap object and TreeMap follow a different syntax like this.
You don't have to. You can write:
HashMap<String, Integer> map = new HashMap<String, Integer>();
... it's just that you usually don't.
Likewise you could write:
Object scanner = new Scanner(System.in);
Basically, there are two types involved:
- The type of the variable you're declaring
- The type whose constructor you're calling
They don't have to be the same, but the constructed type does have to be assignment compatible with the variable type. It has to be a superclass or an interface supported by the class. The point of only specifying a Map
(or List
or whatever) variable as just the interface type is that most of the code should only think about it as a map/list/set/whatever. The fact that it happens to be a HashMap
(or ArrayList
etc) under the covers is an implementation detail.
See "programming to an interface" for more details of this... but stay aware that the syntax is the same in both cases:
VariableType variableName = new ActualTypeBeingConstructed();
I asked my professor. But he did not know the answer.
That scares me...