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
    Rep Power

    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>();
    Java Code:
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    or similarly between these two:
    Java Code:
    List<Integer> l = new ArrayList<Integer>();
    Java Code:
    ArrayList<Integer> l = new ArrayList<Integer>();

    - A.

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

    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 - GameDev tutorials, free Java and JavaScript hosting!
    Static Void Games forum - Come say hello!

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

Similar Threads

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