2

Why we use,

Map abc = new HashMap(20);

instead of

HashMap abc = new HashMap(20);

please help me to find out the differnce between these two.

would be grateful for help.

Vicky
  • 1,175
  • 6
  • 21
  • 43
  • This is somewhat a `code design pattern` in `Java` that you use a `super` type reference whenever possible. here is the same case – Asif May 05 '12 at 07:14
  • You should avoid using raw types and use the generic type `HashMap` or `Map` as much as possible, it will be both more readable and both type safe. – amit May 05 '12 at 07:28
  • possible duplicate of [Java - HashMap vs Map objects](http://stackoverflow.com/questions/1348199/java-hashmap-vs-map-objects) – Louis Wasserman May 05 '12 at 16:12

1 Answers1

5

In the first case, the abc variable is of type HashMap, which is an implementation of the Map interface. If you change your mind later and want to use a TreeMap for instance, you will have to change many references to HashMap in your code, and is is possible you used peculiarities of HashMap where the generic Map operations are enough.

If you use the Map interface as type for you variable, you can change the implementation easily. It is important when you design classes for reuse. If you have a method that takes a Map as argument, any Map implementation will be usable to call your method. Thus, the caller will be free to use the most suitable implementation.

tonio
  • 10,079
  • 2
  • 44
  • 59
  • You might want to check this answer too: http://stackoverflow.com/questions/1348199/java-hashmap-vs-map-objects – tonio May 05 '12 at 07:16
  • Is there any other purpose? It is in general that, we can change the reference whenever we required. – Vicky May 05 '12 at 07:19
  • 1
    I Agree. The question should be "why should I use a `HashMap` and not a `Map`". You should always look for using the highest possible type in the object hirerchy, and have a good reason why not to go one level upper in the hirerchy, not the other way around. – amit May 05 '12 at 07:26