Mends.One

Map and HashMap in Java [duplicate]

Java, Hashmap, Dictionary

I am new to java and came across the following usage for hashmaps :

public static HashMap< String, Integer > Table1;
....
Table1 = new HashMap< String, Integer > ();

.....
public Map<String, Integer> Table2 = new HashMap<String, Integer>();

My question is are the above statement equivalent ? I see Map<String, Integer> is used for Table2. Is HashMap< String, Integer > Table1 and Map<String, Integer> Table2 same programing construct ? Can they be used interchangeably?

-2
S
Shan
Jump to: Answer 1 Answer 2 Answer 3 Answer 4

Answers (4)

Map is an interface, and HashMap is an implementation of it. They're interchangeable in only one direction, meaning that anywhere you can use a Map, you can use a HashMap instead. It goes much beyond that, though, because Map expresses all the operations that any kind of "map" must provide, whether it's a hash-based map (HashMap), a sorting map (TreeMap), a thread-safe map (ConcurrentMap), or an immutable map (ImmutableMap from Guava). Any of those different kinds of maps, and more, can be used wherever a Map is called for. Map itself doesn't provide any of the actual working code. It only says what every kind of map has to be able to do.

Learn more about this relationship from the Java tutorial under "What Is an Interface?" section of the "Object-Oriented Programming Concepts" trail and in the "Interfaces and Inheritance" trail.

2
R
Ryan Stewart

As defined, Table1 must always be a HashMap, but Table2 could be other maps as well.

public Map<String, Integer> Table2 = new HashMap<String, Integer>();
Table2 = new TreeMap<String, Integer>();
Table2 = someFunctionThatReturnsMaps();

The last one is probably the most important, because there are a variety of libraries which return Map types that you would have to cast to HashMap for Table1.

Extra note: General convention is to have variable names start lower case(table1, table2, etc.)

1
T
Thomas

Map is interface and HashMap is implemented class from Map interface.

Interface variable can hold the subclass reference.You can not use interchangeably.

1
P
PSR

Related Questions