2014-11-05 80 views
1

如果我有這樣一個HashMap:安全傳遞HashMap的值,沒有收藏價值逃逸

private final Map<String, Collection<String>> descriptions = new HashMap<>(); 

如何安全值傳遞給外星人的方法? 如果我這樣做:

myOtherObject.outputDesc(descriptions.values()); 

然後myOtherObject可能改變的值。

這樣做是否安全嗎?

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

回答

2

按照您的建議創建集合的副本是一種可行的方法。但是不需要複製列表的額外工作。 Java爲preventing value changes提供了更方便的方式:

myOtherObject.outputDesc(Collections.unmodifiableCollection(descriptions.values()));