[英]Best practice: how to return keyset of a map from a method in java
My function returns a keyset of a HashMap member. 我的函数返回HashMap成员的键集。
From the JavaDoc : 从JavaDoc :
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
该集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。
I want to avoid this behavior. 我想避免这种行为。
I want to return an unmodifiable set, perhaps a copy of the set. 我想返回一个不可修改的集合,也许是该集合的副本。
I do not want changes to the set or map to be reflected in one another. 我不希望对设置或地图的更改相互反映。
Are there any best practices to deal with such a situation? 是否有最佳实践来应对这种情况?
Personally, I'd go with Google's Guava - especially for I want to return an unmodifiable set, perhaps a copy of the set. 就个人而言,我会选择Google的Guava-特别是因为我想退回一套不可修改的套装,也许是套装的副本。 - if the map grows,
ImmutableSet
won't exhibit growth: -如果地图增长,则
ImmutableSet
将不会增长:
ImmutableSet.copyOf(map.keySet());
Or if you want to use the standard Java API - NOTE the resulting Set
will grow as your Map
grows: 或者,如果您想使用标准的Java API-注意,结果
Set
将随着Map
增长而增长:
Collections.unmodifiableSet(map.keySet());
Using either of the above is considered good practice given your requirements. 鉴于您的要求,使用以上两种方法均被视为一种良好的做法。
The standard approach is to return a copy, typically using a copy constructor : 标准方法是返回副本,通常使用副本构造函数 :
Here's a utility method you can use: 您可以使用以下实用程序方法:
public static <K, V> Set<Map.Entry<K, V>> copyKeys(Map<K, V> map) {
return new HashSet<Map.Entry<K, V>>(map.keySet());
}
You can use standard Collections.unmodifiableSet
which is designed exactly for that. 您可以使用专门为此设计的标准
Collections.unmodifiableSet
。 Attempts to modify the wrapped Set will end up in UnsupportedOperationException
尝试修改包装的Set最终将导致
UnsupportedOperationException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.