gpt4 book ai didi

java - 克隆 ConcurrentHashMap

转载 作者:行者123 更新时间:2023-12-01 04:32:40 29 4
gpt4 key购买 nike

为什么我不能克隆 ConcurrentHashMap ?

ConcurrentHashMap<String, String> test = new ConcurrentHashMap<String, String>();
test.put("hello", "Salaam");

ConcurrentHashMap<String, String> test2 = (ConcurrentHashMap<String, String> ) test.clone();

System.out.println(test2.get("hello"));

如果我使用 HashMap而不是 ConcurrentHashMap , 有用。

最佳答案

clone()方法在 AbstractMap不是用于复制,它是一种内部方法,请注意 protected 关键字。

protected Object clone() throws CloneNotSupportedException {
HashMap正好有个公众号 clone(),但这并不意味着您应该使用它, Effective Java: Analysis of the clone() method 对此进行了进一步讨论。

创建集合副本的一种更灵活的方法是通过复制构造函数。这些具有从任何其他创建任何 Map 实现的优势。
/**
* Creates a new map with the same mappings as the given map.
*
* @param m the map
*/
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {

例如
ConcurrentHashMap<String, String> original = new ConcurrentHashMap<String, String>();
original.put("hello", "Salaam");

Map<String, String> copy = new ConcurrentHashMap<>(original);
original.remove("hello");
System.out.println(copy.get("hello"));

关于java - 克隆 ConcurrentHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417830/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com