Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By jim829

Thread: Hashmap vs. Map (in terms of their types)

  1. #1
    Join Date
    Oct 2016
    Posts
    24
    Rep Power
    0

    Default Hashmap vs. Map (in terms of their types)

    In the attached screenshot, we have a new "Hashmap" object being assigned to the variable called personMap which is of type Map<Integer, Person>.

    Shouldn't the type of the personMap object variable be "Hashmap?" Why is it different?
    Attached Thumbnails Attached Thumbnails Hashmap vs. Map (in terms of their types)-types.png  

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    5,847
    Rep Power
    10

    Default Re: Hashmap vs. Map (in terms of their types)

    It can be but it doesn't have to. HashMap implements the Map interface and it is usually best practice to assign the implementation to the
    interface type. Exceptions are when the implementation provides additional methods one wants to use. The idea is that it makes writing code easier. If you start assigning everything to a HashMap type and decide you want to use a TreeMap, you need to change all HashMap types to TreeMap types. If you simply use the Map reference, you probably need to change it in fewer places.

    In a related topic, it is best to pass the interface type to a method rather than the implementation.

    Regards,
    Jim
    Last edited by jim829; 01-06-2017 at 06:16 AM.
    SurfMan likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 1
    Last Post: 05-12-2016, 09:24 AM
  2. Replies: 7
    Last Post: 12-08-2009, 08:17 PM
  3. Java terms
    By Shaolin in forum New To Java
    Replies: 2
    Last Post: 12-27-2007, 06:02 PM

Tags for this Thread

Posting Permissions

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