简体   繁体   中英

Dynamically adding distinct sets of Integers

I am writing a program where a user adds a set of numbers with a name and a set of values, in this format:

Example:

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

I am to extract the name (set1), and pass that to a new Set. Then add the numbers to the set.

Normally, it would be easy to just make a new Set and add the numbers. For example:

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

My confusion is with the fact that every time a user adds a new set with a new name, it would need a unique variable name, but I can't change that dynamically in my code.

For instance if a user issues the command

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

ideally I could do this:

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

But I know this is not possible. So given that I can't have unique variable names for each set, how do I distinguish between created sets when I want to add numbers to them?

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

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

Maybe a HashMap would work?

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

You would load up all of the integers into the set. Then you'd load them into the map with

sets.put(*somestring*, *aset*);

Then retrieve with

sets.get(*somestring*);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM