Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By KevinWorkman

Thread: Constructing a HashMap

  1. #1
    azalea is offline Member
    Join Date
    Oct 2011
    Posts
    12
    Rep Power
    0

    Default Constructing a HashMap

    Hi All,
    I'm wondering about the precise difference between the following two constructions:
    Java Code:
    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    and
    Java Code:
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    or similarly between these two:
    Java Code:
    List<Integer> l = new ArrayList<Integer>();
    and
    Java Code:
    ArrayList<Integer> l = new ArrayList<Integer>();
    Cheers,

    - A.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,037
    Rep Power
    10

    Default 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.
    azalea likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    azalea is offline Member
    Join Date
    Oct 2011
    Posts
    12
    Rep Power
    0

Similar Threads

  1. Hepl me in constructing program
    By saideepak in forum Advanced Java
    Replies: 4
    Last Post: 01-11-2011, 05:18 AM
  2. Replies: 7
    Last Post: 12-08-2009, 08:17 PM
  3. Constructing the Interface!
    By myskynim in forum New To Java
    Replies: 3
    Last Post: 11-19-2009, 10:51 AM
  4. Constructing simple Servlet
    By herbozo2003 in forum Java Servlet
    Replies: 1
    Last Post: 03-02-2009, 12:35 PM
  5. Need help with constructing code
    By Nine0joe in forum New To Java
    Replies: 6
    Last Post: 05-09-2008, 03:14 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •