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.
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:
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...
Map is an interface (or more general class) - TreeMap is something that implements Map (or is a more specific class).
e.g. List is a general interface, ArrayList implements List so you can say
List<Obj> list = new ArrayList<Obj>();
// or
ArrayList<Obj> list = new ArrayList<Obj>();
// but not
ArrayList<Obj> list = new List...
If your professor really can't answer this, you really need to get a new Professor!!
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