quakkels quakkels - 3 months ago 14
Java Question

Why was Map<> in Java designed to require two types; Map<> and HashMap<>?

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.

Answer

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>();