How to initialize HashSet values by construction?
To initialize the values of a HashSet
when constructing the set, you can use one of the HashSet
constructors that takes a Collection
as an argument.
For example, you can use the following code to create a HashSet
with the values "apple"
, "banana"
, and "cherry"
:
Set<String> set = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));
This creates a new HashSet
object and initializes it with the elements of the Collection
created by the Arrays.asList
method.
You can also use this technique to initialize a HashSet
with the elements of another set or a list:
Set<String> set1 = new HashSet<>(Arrays.asList("apple", "banana", "cherry"));
Set<String> set2 = new HashSet<>(set1);
List<String> list = Arrays.asList("apple", "banana", "cherry");
Set<String> set3 = new HashSet<>(list);
In these examples, set2
and set3
are both initialized with the same elements as set1
.
You can also use the addAll
method to add the elements of a Collection
to an existing HashSet
. For example:
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("apple", "banana", "cherry"));
This code creates an empty HashSet
and then adds the elements of the Collection
created by the Arrays.asList
method to the set.