0

Possible Duplicate:
Java - HashMap vs Map objects

whats the different between

private Map<String, Integer> drawableMap = new HashMap<String, Integer>();

and

private HashMap<String, Integer> drawableMap = new HashMap<String, Integer>();
Community
  • 1
  • 1

2 Answers2

1

The type of the variable at the left-hand side of your assignment expression has nothing to do with object creation; therefore in both cases you are creating the exact same object. Since in Java you can only store a reference to an object into a variable, the type of that variable constrains the types of object the variable can refer to. In the first case it can refer to any object that implements Map; in the second, only HashMap objects are acceptable.

The other consequence is that in the first case you can only call methods of HashMap that are declared in the Map interface, whereas in the second case you can call any additional methods specific to the HashMap implementation.

In most real-world cases you will prefer the first case since you almost never need implementation-specific methods. The same rule goes for the complete Collections Framework.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

In the first example, you can later assign drawableMap to other implementations of Map (e.g. LinkedHashMap). In the second example, you cannot - you are confined to HashMaps (and any of its subclasses). Generally, the first approach would be preferred over the second as it would provide greater flexibility down the road.

Ultimately, the first statement creates a variable of type Map that is an instance of HashMap. The second creates a variable of type HashMap that is also an instance of HashMap.

arshajii
  • 127,459
  • 24
  • 238
  • 287