问题描述:

While passing a set to create a new set in java,any modifications made to the new set also modifies the original set.How do I pass the set so that any changes made to the new one doesn't affect the original one?

网友答案:
Set newSet = new HashSet(oldSet);

This makes a copy of the old set; any changes made to old set after this do not affect the new set.

网友答案:

It would depend on the implementation of the Set, but if you check the Set API, all known implementing Classes, in those where that constructor is implemented, it says Constructs a new Set.

You can check it for:

HashSet:

Constructs a new set containing the elements in the specified collection.

TreeSet:

Constructs a new tree set containing the elements in the specified collection, [...]

LinkedHashSet:

Constructs a new linked hash set with the same elements as the specified collection.

etc.

网友答案:

Here's what i was looking for:

new HashSet<String>(Arrays.asList(new String[]{"one","two"}));
相关阅读:
Top