Win a copy of High Performance Python for Data Analytics this week in the Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Why developer use "Map m= new HashMap()" or "List l = new ArrayList()"?

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Techies,

Sorry if this question is repeated ...I have searched but havent got this one...

Why developer use "Map m= new HashMap()" or "List l = new ArrayList()" in place of HashMap hm= new HashMap()" or "ArrayList al = new ArrayList()"

According to me Map or List is interface and it is hidding the implementation from client.


Please give your inputs and share your knowledge for this question.


Thank You,
Rahul
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have a look at this article: Program to an interface, not an implementation

The main reason to do this is to decouple your code from a specific implementation of the interface. By writing your code like this:

then the rest of your code only knows that data is a Map<String, Object>, which is good, because it you can now easily change to a different implementation of interface Map if necessary. You'd only need to change that one line of code, for example to:

For the rest of your program, nothing changes - data is still a Map<String, Object>.

If you would have written:

then changing it would have been much harder, because the rest of your code might have used methods that are specific to HashMap.
 
Rahul Sud
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jesper for good explanation:)
 
reply
    Bookmark Topic Watch Topic
  • New Topic