如何在 Java 中克隆 Map


java.util.HashMap 類是基於雜湊表的 Map 介面的實現。若要克隆 Java 中的 Map,請使用 clone() 方法。

舉例

我們看一個克隆 Map 的例子 −

import java.util.*;
public class HashMapDemo {
   public static void main(String args[]) {
      // create two hash maps
      HashMap newmap1 = new HashMap();
      HashMap newmap2 = new HashMap();
      // populate 1st map
      newmap1.put(1, "This");
      newmap1.put(2, "is");
      newmap1.put(3, "it!");
      // clone 1st map
      newmap2 = (HashMap)newmap1.clone();
      System.out.println("1st Map: " + newmap1);
      System.out.println("Cloned Map: " + newmap2);
   }
}

輸出

1st Map: {1=This, 2=is, 3=it!}
Cloned Map: {1=This, 2=is, 3=it!}

更新於: 2019 年 9 月 24 日

399 次觀看

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.