java 使用工具类创建集合
时间: 2023-08-18 19:06:28 浏览: 85
在 Java 中使用工具类创建集合可以使用 `java.util.Collections` 类中的静态方法。下面是一些常用的方法示例:
1. 创建一个空的集合:
```java
List<String> emptyList = Collections.emptyList(); // 创建一个空的 List
Set<Integer> emptySet = Collections.emptySet(); // 创建一个空的 Set
```
2. 创建一个只包含一个元素的集合:
```java
List<String> singletonList = Collections.singletonList("element"); // 创建一个只包含一个元素的 List
Set<Integer> singletonSet = Collections.singleton(10); // 创建一个只包含一个元素的 Set
```
3. 创建一个具有指定元素的不可变集合:
```java
List<String> immutableList = Collections.unmodifiableList(List.of("element1", "element2")); // 创建一个不可变的 List
Set<Integer> immutableSet = Collections.unmodifiableSet(Set.of(1, 2, 3)); // 创建一个不可变的 Set
```
4. 创建一个可变集合并添加元素:
```java
List<String> mutableList = new ArrayList<>(); // 创建一个可变的 List
mutableList.add("element1");
mutableList.add("element2");
Set<Integer> mutableSet = new HashSet<>(); // 创建一个可变的 Set
mutableSet.add(1);
mutableSet.add(2);
mutableSet.add(3);
```
这些方法可以帮助你使用工具类快速创建并操作集合。注意,不可变集合在创建后不能修改其内容,而可变集合可以随时添加、删除和修改元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)