将hashset放入hashmap中

hmmo2u0o  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(366)

有没有办法通过将哈希集添加到hashmap中,然后在不更改放置到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以供用户再次使用。但我需要使用相同的哈希集,因为会有一个循环。

bsxbgnwa

bsxbgnwa1#

我建议您不要清除hashmap,而是在循环继续时将hashset的新示例添加到hashmap中。就像下面一样。

public static void hash() {
HashMap<Integer, HashSet<Integer>> hset = new HashMap<Integer, HashSet<Integer>>()
int mapKey = 1;
//loop here , create the instance of HashSet for every loop operation
while(true){
HashSet<Integer> list = new HashSet<Integer>();

list.add(1);
list.add(2);
list.add(3);
list.add(4);
hset.put(mapKey,list);

System.out.println(hset.get(mapKey));
// the console prints "[1, 2, 3, 4]"
//list.clear();

System.out.println(hset.get(map.getKey));
// the console prints "[]"
mapKey++;
  }
}

mapkey对于您将拥有的不同hashset是不同的。

im9ewurl

im9ewurl2#

放一个新的 HashSet 由以下元素组成 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<> .

pinkon5k

pinkon5k3#

参数传递在java中是通过引用完成的。 HashSet 在你的 Hashmap 以及 HashSet 中的对象 list 变量是一样的!

相关问题