Results 1 to 3 of 3
Thread: Constructing a HashMap
- 11-03-2011, 03:11 PM #1
Member
- Join Date
- Oct 2011
- Posts
- 12
- Rep Power
- 0
Constructing a HashMap
Hi All,
I'm wondering about the precise difference between the following two constructions:
andJava Code:HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
or similarly between these two:Java Code:Map<Integer,Integer> map = new HashMap<Integer,Integer>();
andJava Code:List<Integer> l = new ArrayList<Integer>();
Cheers,Java Code:ArrayList<Integer> l = new ArrayList<Integer>();
- A.
- 11-03-2011, 03:17 PM #2
Re: Constructing a HashMap
The short answer is: very little.
The slightly longer answer is: ArrayList is a List, and HashMap is a Map. List and Map are interfaces. Other things can also be Lists, and other things can also be Maps. It's generally a good idea to save things as non-specific as possible (so Map instead of HashMap), because it makes it much easier to go back and make changes later. This is called "programming to interfaces". List and Map are both interfaces.
For example, say you have a class that contains a HashMap, and then a bunch of methods that take a HashMap as a parameter. But then you want to change that HashMap to a different kind of Map (say a TreeMap). Now you have to change not only the variable declaration, but also every single method that uses it. If instead you had saved the HashMap as a Map reference, and the methods had taken Map arguments as parameters, you would only have to make that change in one place.How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 11-03-2011, 03:19 PM #3
Member
- Join Date
- Oct 2011
- Posts
- 12
- Rep Power
- 0
Similar Threads
-
Hepl me in constructing program
By saideepak in forum Advanced JavaReplies: 4Last Post: 01-11-2011, 04:18 AM -
How to create a new HashMap from a HashMap entries of other methods
By pandeyalok in forum Advanced JavaReplies: 7Last Post: 12-08-2009, 07:17 PM -
Constructing the Interface!
By myskynim in forum New To JavaReplies: 3Last Post: 11-19-2009, 09:51 AM -
Constructing simple Servlet
By herbozo2003 in forum Java ServletReplies: 1Last Post: 03-02-2009, 11:35 AM -
Need help with constructing code
By Nine0joe in forum New To JavaReplies: 6Last Post: 05-09-2008, 02:14 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks