Java创建三个map_在 Java 中如何创建 HashMap 对象?

本文介绍了Java中HashMap类的构造方法,包括默认构造函数创建空HashMap对象的方法,以及如何通过现有Map对象(如TreeMap或HashMap)创建新的HashMap对象。文章还提供了具体的代码示例来展示如何复制TreeMap和HashMap。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值