Java 安全地传递HashMap值,而无需转义值集合
如果我有这样一个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
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()));