Sawyer
Sawyer

Reputation: 443

What does HashMap(Map m) constructor does?

I have come across a piece of code where I found

  public class MapImpl {
   private static MapImpl mpl = new MapImpl();
     Map<String,String> hm;
     private MapImpl() {
          hm = new HashMap<>();
       }
     public addContentsToMap(Map<String,String> m){
         this.hm=m;
     }
     public Map returnMap(){
         new HashMap<>(hm);
       }
    }

I like to know here that when the default constructor is called the map is initialized to hashmap, and when addContentsToMap is called a map is formed with values.

I see that the returnMap uses the constructor of the HashMap(Map m). I have gone through the source code of HashMap but was clueless.

Upvotes: 1

Views: 380

Answers (1)

xenteros
xenteros

Reputation: 15852

It takes any implementation of Map interface and constructs a HashMap which also is an implementation of Map interface.

Developers like Hash-Collections (HashSet, HashMap etc.) including HashMap because they provide expected O(1) get and contains time.

It can be useful, once you have a Map which isn't a HashMap (e.g. Properties) and you know that it'll be large and you will read from it many times, it's useful to switch to a different implementation of a Map.

Documentation:

public HashMap(Map<? extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.

Parameters:

m - the map whose mappings are to be placed in this map

Throws:

NullPointerException - if the specified map is null

Upvotes: 4

Related Questions