My primary language has been C#, though lately I've been doing more Java development. In C#, I can define a Dictionary like this:
using System.Collections.Generic;
...
Dictionary<string, string> myDict = new Dictionary<string, string>();
However, if I want to create a similar object in Java, I need to do this:
import java.utils.Map;
import java.utils.HashMap;
...
Map<String, String> myMap = new HashMap<String, String>();
Why is Java designed so that Map<>
is created with a HashMap<>
and two different imports are required to use it?
Just curious.
Update
It never even crossed my mind that Map
could be an interface. It doesn't follow the convention of prefixing the interface name with an I
. I'm surprised that such a convention isn't used there.
4 Answers 4
Map
is an interface, while HashMap
is a concrete implementation, just like TreeMap
BTW You can use only HashMap
if you like:
HashMap<k,v> hashmap = new HashMap<k,v>();
Comments
Map is an interface that HashMap implements. enter image description here
We can do ,
HashMap<String, String> map = new HashMap<String, String>();
and
Map<String, String> map = new HashMap<String, String>();
The advantage to using Map<String, String>
is that you can change the underlying object to be a different kind of map without breaking your contract with any code that's using it. If you declare it as HashMap<String, String>
, you have to change your contract if you want to change the underlying implementation.
Comments
It wasn't 'designed to require two types', but it is an interface, and any interface requires an implementing class somewhere.
Comments
As others said, Map is an interface that HashMap implements.
Java contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap
Map<String, String> myMap = new HashMap<String, String>();
will only allow the use of functions defined in the Map
interface, while
HashMap<String, String> myMap = new HashMap<String, String>();
will allow the use of all public functions in HashMap (Map interface methods + hashMap methods).
update from the oracle website: http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap. Their behavior and performance are precisely analogous to HashSet, TreeSet, and LinkedHashSet, as described in The Set Interface section.
but as mentioned in the comments below, java has actually more Map implementations: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
8 Comments
Map
lists all of the ones that come with the JDK.
HashMap<String, String> myMap = new HashMap<String, String>();
and then you only need one import.IDictionary
interface just that way. The statementusing System.Collections.Generic
makes bothIDictionary
andDictionary
available, because they are both in that namespace, so only oneusing
is needed. It is similar to the way thatimport java.utils.*
does the job for bothMap
andHashMap
.