Java 中的 HashMap 类提供了几个构造方法来创建对象。下面的例子演示了如何使用默认构造函数创建一个新的空 HashMap 对象。
HashMap hmap = new HashMap();
此 Hashmap 对象的键和值都是 String 类型。
下面重载的 HashMap 构造方法可以根据现有的 Map 对象(如 TreeMap 或 HashMap)创建一个新的 HashMap对象。
public HashMap(Map extends K,? extends V> anotherMap)
这个构造方法创建的 HashMap 对象与指定的 Map 对象具有相同的键值对。
如何使用 HashMap 构造方法将 TreeMap 复制到HashMap?
TreeMap tmap = new TreeMap();
tmap.put(3, "Three");
tmap.put(1, "One");
tmap.put(2, "Two");
/*
* This will copy all the mappings of the TreeMap to HashMap object
*/
HashMap hmap = new HashMap(tmap);
System.out.println(hmap);
输出:
{1=One, 2=Two, 3=Three}
如何使用 HashMap 构造方法将 HashMap 复制到另一个 HashMap?
和上面给出的示例类似,也可以使用此构造方法将 HashMap 对象复制到另一个 HashMap 对象:
HashMap hmap = new HashMap();
hmap.put(1, "One");
hmap.put(2, "Two");
hmap.put(3, "Three");
/*
* This will copy all the mappings of the HashMap to another HashMap object
*/
HashMap hmapCopy = new HashMap(hmap);
System.out.println(hmapCopy);
输出:
{1=One, 2=Two, 3=Three}