【发布时间】:2021-04-04 14:15:36
【问题描述】:
graph = {1:{'a','b'},2:{'c','d'},3:{'e','f'},4:{'g','h'},5:{'b','d'},6:{'b','e'},7:{'a','c'},8:{'f','h'},9:{'e','g'}}
我做了什么:
public class Try {
public static void main(String[] args) {
Set<Character> universal = new HashSet<>();
Collections.addAll(universal, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
// System.out.println(universal);
HashMap<Integer, HashSet<Character>> graph =
new HashMap<Integer, HashSet<Character>>();
HashSet<Character> values = new HashSet<Character>();
Collections.addAll(values, 'a', 'b');
System.out.println(values);
// Output : [a, b]
graph.put(1, values);
System.out.println(graph.get(1));
// Output : [a, b]
System.out.println(graph);
// Output : {1=[a, b]}
values.removeAll(values);
System.out.println(graph.get(1));
// Output : []
// Why did the value clear out from the graph?
System.out.println(graph);
// Output : {1=[]}
}
}
如何一次放置这些值而不是一直使用put() 函数?没有更好的方法吗?另外,解释为什么在变量 values 上使用 clear() 或 remove() 函数会导致它从变量 graph 中删除。我希望结构是可变的。
【问题讨论】:
标签: java collections hashmap hashset