企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 用 Java 克隆`HashMap` > 原文: [https://beginnersbook.com/2014/08/clone-a-hashmap-in-java/](https://beginnersbook.com/2014/08/clone-a-hashmap-in-java/) #### 描述 克隆`HashMap`的程序。我们将使用`HashMap`类的以下方法来执行克隆。 `public Object clone()`:返回此`HashMap`实例的浅表副本:未克隆键和值本身。 #### 示例 ```java import java.util.HashMap; class HashMapExample{ public static void main(String args[]) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); // Adding few elements hmap.put(11, "Jack"); hmap.put(22, "Rock"); hmap.put(33, "Rick"); hmap.put(44, "Smith"); hmap.put(55, "Will"); System.out.println("HashMap contains: "+hmap); // Creating a new HashMap HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); // cloning first HashMap in the second one hmap2=(HashMap)hmap.clone(); System.out.println("Cloned Map contains: "+hmap2); } } ``` **输出:** ```java HashMap contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith} Cloned Map contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith} ```