This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
You may decide later to use a TreeMap instead of a HashMap. By referreing to the interface instead of the implementation, you can make that change with one line of code and not break any code dependent on that Map.
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Originally posted by Saumya Kiran: What is the advantage of using Map map = new HashMap() vs HashMap map = new HashMap()
by using the interface Map as a reference to your instance of HashMap, it is easier to rewrite your code later on to use a different type of map. since every method call is specified by the interface, you could change HashMap to TreeMap, and not have to rewrite your code. If there is some specific function in HashMap that you need, and will never need to change the Map type, then it shouldn't be a problem to just declare it as HashMap.
use the [CODE] tags - it makes it much easier for people to help you.
This is known as the "program to the interface, not to the implementation" rule. The advantage is to swap your object implementations without affecting the code where this object is used. For example, if you have code like this:
The way it is coded, the caller of that method must pass an instance of a HashMap to it, otherwise the compiler will generate an error. Now, suppose that you have 100 methods like this, and you decided not to use a HashMap anymore, but a TreeMap (for optimization purposes). You now must change your code in 100 different places. Now compare it with this code:
Notice that if you want to replace your HashMap with a TreeMap, you only need to make a change in only one place, where a map is instantiated. Isn't this beautiful?
Joined: Jan 30, 2002
Damn Jon and Eugene don't it feel good when we're all on the same page with a simulpost!
Joined: Oct 08, 2001
Damn Jon and Eugene don't it feel good when we're all on the same page with a simulpost! Fu**ing amazing!
Joined: Apr 28, 2003
Thanks all for the replies. I wanted to know why I had to make the changes before I changed my code --Saumya.
In addition to making future changes easier, you can make current transformaions possible. This example was from a JDC Tech Tips that loads up a low-overhead HashMap and then converts it to a sorted TreeMap.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi