quakkels quakkels - 4 months ago 19
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
is created with a
and two different imports are required to use it?

Just curious.


It never even crossed my mind that
could be an interface. It doesn't follow the convention of prefixing the interface name with an
. I'm surprised that such a convention isn't used there.


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