Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 安全地传递HashMap值,而无需转义值集合_Java_Thread Safety_Encapsulation - Fatal编程技术网

Java 安全地传递HashMap值,而无需转义值集合

Java 安全地传递HashMap值,而无需转义值集合,java,thread-safety,encapsulation,Java,Thread Safety,Encapsulation,如果我有这样一个hashmap: private final Map<String, Collection<String>> descriptions = new HashMap<>(); 然后myOtherObject可以更改这些值 这样做安全吗 myOtherObject.outputDesc(new ArrayList<>(descriptions .values())); myOtherObject.outputDesc(新的Array

如果我有这样一个hashmap:

private final Map<String, Collection<String>> descriptions = new HashMap<>();
然后myOtherObject可以更改这些值

这样做安全吗

myOtherObject.outputDesc(new ArrayList<>(descriptions .values()));
myOtherObject.outputDesc(新的ArrayList(descriptions.values());

按照您的建议创建收藏的副本是一种可行的方法。但复制列表不需要额外的努力。Java为以下方面提供了更方便的方法:

myOtherObject.outputDesc(new ArrayList<>(descriptions .values()));
myOtherObject.outputDesc(Collections.unmodifiableCollection(descriptions.values()));