1.最普通的初始化方式:先创建,然后再添加元素
Set<String> set = new HashSet<>();
set.add("aaa");
set.add("aaa.apk");
set.add("aaa(1).apk");
2.使用Arrays.asList与构造函数
你可以先使用Arrays.asList将元素转化为列表,然后通过构造函数将其转化为Set。
Set<String> stringSet = new HashSet<>(Arrays.asList("element1", "element2", "element3"));
3.使用Collections.addAll
这种方法允许你创建一个空的Set,然后通过Collections.addAll方法添加元素。
Set<String> stringSet = new HashSet<>();
Collections.addAll(stringSet, "element1", "element2", "element3");
4.使用Java 8 的Stream
可以利用Stream的of方法,然后通过collect收集器来收集元素到Set中。
Set<String> stringSet = Stream.of("element1", "element2", "element3")
.collect(Collectors.toSet());
5.使用Java 9+的Set.of
从Java 9开始,Set接口中添加了of方法,可以方便地创建一个不可修改的集合。
Set<String> stringSet = Set.of("element1", "element2", "element3");
6.利用匿名内部类和实例初始化块
public static void main(String[] args) {
Set<Character> set = new HashSet() { // 这个括号用来创建匿名内部类
{ // 这个括号表示是匿名内部类的实例初始化块
add('a');
add('b');
add('c');
}
};
System.out.println(set); // [a, b, c]
System.out.println(set.contains('a')); // true
}
这些方法各有用途,选择哪种取决于你的具体需求,比如是否需要可修改的集合,以及你使用的Java版本。