动态添加不同的整数集

Dynamically adding distinct sets of Integers

我正在编写一个程序,用户可以在其中添加一组带有名称和一组值的数字,格式如下:

示例:

添加组 1:{1,3,5,7}[​​=13=]

我要提取名称 (set1),并将其传递给新的 Set。然后将数字添加到集合中。

通常情况下,只需制作一个新的集合并添加数字就很容易了。例如:

Set<Integer> newSet = new Set<Integer>();
newSet.add(1);
newSet.add(3);
newSet.add(5);
newSet.add(7);

我感到困惑的是,每次用户添加一个新名称的新集合时,它都需要一个唯一的变量名称,但我无法在我的代码中动态更改它。

例如,如果用户发出命令

add set1:{1,3,5,7} 

理想情况下我可以这样做:

Set<Integer> set1 (variable name taken from user input) = new Set<Integer>();

但我知道这是不可能的。所以鉴于我不能为每个集合设置唯一的变量名称,当我想向它们添加数字时如何区分创建的集合?

您可以使用集合名称作为键来使用集合映射:

Map<String, Set<Integer>> map = new HashMap<String, Set<Integer>>();

也许 HashMap 会起作用?

HashMap<String, Set<Integer>> sets = new HashMap<String, Set<Integer>();

您会将所有整数加载到集合中。然后你用

将它们加载到地图中
sets.put(*somestring*, *aset*);

然后用

检索
sets.get(*somestring*);