[英]Non-backed Key Set of Java Map
Given the following Java HashMap
: 给定以下Java
HashMap
:
HashMap<String, Integer> map = new HashMap<String, Integer>();
The following statement gives me a 'backed' set of the maps keys: 以下语句为我提供了一组“支持”的地图钥匙:
Set<Integer> keys = map.keySet();
but suppose I'd like a copy of the key set which I can manipulate without affecting the map. 但是假设我想要一个密钥集的副本,可以在不影响地图的情况下进行操作。 Is there a better/more correct way than
有没有比这更好/更正确的方法
Set<Integer> keys = new HashSet<Integer>();
for( Integer key : map.keySet() )
keys.add( key );
? ?
There's a slightly simpler way: 有一种更简单的方法:
Set<Integer> keys = new HashSet<Integer>(map.keySet());
...which just makes a copy in a single line. ...仅在一行中复制一份。
Set<Integer> keys = new HashSet<Integer>(map.keySet());
这将初始化一个Set,该Set包含与传递给HashSet构造函数的地图键集中的元素完全相同的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.