将HashSet放入HashMap中 [英] Putting HashSet inside a HashMap
问题描述
是否有任何方法可以通过将哈希集添加到HashMap中,然后在不更改先前放置在hashMap中的HashSet的情况下更改HashSet的方式进行重用?
Is there any way to reuse a hash set by adding it to the HashMap, then later changing the HashSet without it changing the previous HashSet that was placed into the hashMap?
public static void hash() {
HashMap<Integer, HashSet<Integer>> hset = new HashMap<Integer, HashSet<Integer>>(
HashSet<Integer> list = new HashSet<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
hset.put(1,list);
System.out.println(hset.get(1));
// the console prints "[1, 2, 3, 4]"
list.clear();
System.out.println(hset.get(1));
// the console prints "[]"
}
我想获取HashSet的用户输入,将其存储在HashMap中,然后清除要由用户再次使用的HashSet.但是我需要使用相同的HashSet,因为会有一个循环.
I want to take user inputs for the HashSet, store them in the HashMap, then clear the HashSet to be used again by the user. But I need to use the same HashSet as there will be a loop.
推荐答案
放入一个新的 HashSet
,该列表由 list
的元素组成.
Put a new HashSet
consisting of the elements of list
.
hset.put(1, new HashSet<>(list));
演示:
import java.util.HashMap;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashMap<Integer, HashSet<Integer>> hset = new HashMap<>();
HashSet<Integer> list = new HashSet<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
hset.put(1, new HashSet<>(list));
System.out.println(hset.get(1));
// the console prints "[1, 2, 3, 4]"
list.clear();
System.out.println(hset.get(1));
// the console prints "[1, 2, 3, 4]"
}
}
在旁注中,您只需要在右侧<>
即可,即可以代替 new HashMap< Integer,HashSet< Integer>>
只需编写 new HashMap<>
.
On a side note, you need just <>
on the right side i.e. instead of new HashMap<Integer, HashSet<Integer>>
, you can simply write new HashMap<>
.
这篇关于将HashSet放入HashMap中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!