一、使用putAll()方法
Java中提供了putAll()方法,可以將一個Map中的所有鍵值對複製到另一個Map中。示例如下:
Map<String, Integer> sourceMap = new HashMap<>(); sourceMap.put("key1", 1); sourceMap.put("key2", 2); Map<String, Integer> targetMap = new HashMap<>(); targetMap.putAll(sourceMap);
以上代碼中,首先創建了一個sourceMap,並往其中放入兩個鍵值對;接著創建一個空的targetMap,並使用putAll()方法將sourceMap中的鍵值對全部複製到targetMap中。
二、使用構造函數
除了使用putAll()方法,還可以使用Map的構造函數來實現複製功能。示例代碼如下:
Map<String, Integer> sourceMap = new HashMap<>(); sourceMap.put("key1", 1); sourceMap.put("key2", 2); Map<String, Integer> targetMap = new HashMap<>(sourceMap);
以上代碼中,我們在創建targetMap的時候直接將sourceMap作為參數,這樣就會將sourceMap中的所有鍵值對複製到targetMap中。
三、使用put()方法
如果需要複製一個Map中的部分鍵值對,可以使用put()方法進行複製。示例代碼如下:
Map<String, Integer> sourceMap = new HashMap<>(); sourceMap.put("key1", 1); sourceMap.put("key2", 2); Map<String, Integer> targetMap = new HashMap<>(); targetMap.put("key3", sourceMap.get("key1")); targetMap.put("key4", sourceMap.get("key2"));
以上代碼中,我們創建了一個sourceMap,並往其中放入兩個鍵值對;接著創建了一個空的targetMap,並使用put()方法將sourceMap中的兩個鍵值對分別複製到了targetMap中。
四、使用clone()方法
Java中的Map是一個介面,在使用時需要實現具體的類。如果實現的類實現了Cloneable介面,就可以使用clone()方法進行複製。示例代碼如下:
Map<String, Integer> sourceMap = new HashMap<>(); sourceMap.put("key1", 1); sourceMap.put("key2", 2); Map<String, Integer> targetMap = (HashMap<String, Integer>) sourceMap.clone();
以上代碼中,我們創建了一個sourceMap,並往其中放入兩個鍵值對;接著創建了一個空的targetMap,並使用clone()方法將sourceMap複製到了targetMap中。
五、使用Apache Commons Collections庫
Apache Commons Collections提供了一個工具類MapUtils,其中包含很多與Map相關的方法,其中就包括了複製Map的方法。使用方法如下:
Map<String, Integer> sourceMap = new HashMap<>(); sourceMap.put("key1", 1); sourceMap.put("key2", 2); Map<String, Integer> targetMap = MapUtils.clone(sourceMap);
以上代碼中,我們創建了一個sourceMap,並往其中放入兩個鍵值對;接著使用MapUtils的clone()方法將sourceMap複製到了targetMap中。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195925.html