Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Syntax for creating HashMap and TreeMap objects

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.

like image 469
Nicholas Avatar asked Sep 23 '26 23:09

Nicholas


2 Answers

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...

like image 134
Jon Skeet Avatar answered Sep 25 '26 17:09

Jon Skeet


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!!

like image 44
John3136 Avatar answered Sep 25 '26 17:09

John3136