Normally, when you create an object you provided the same type in front
like:
Scanner scanner = new Scanner(System.in);
but declaring a HashMap object and TreeMap follow a different syntax like this.
Map m1 = new HashMap();
SortedMap sm = new TreeMap();
What is the reason? I asked my professor. But he did not know the answer.
You don’t have to. You can write:
… it’s just that you usually don’t.
Likewise you could write:
Basically, there are two types involved:
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(orListor 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 aHashMap(orArrayListetc) 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:
That scares me…