java集合如何赋值
集合赋值方法
在Java中,集合赋值可以通过多种方式实现,具体取决于集合类型和使用场景。以下是常见的几种方法:
直接初始化赋值
使用大括号{}可以在声明时直接初始化集合(仅适用于List):
List<String> list = new ArrayList<>() {{ add("A"); add("B"); }};
使用Arrays工具类
通过Arrays.asList()快速创建List:
List<String> list = Arrays.asList("A", "B", "C");
使用Collections工具类
Collections.addAll()方法可以批量添加元素:
List<String> list = new ArrayList<>();
Collections.addAll(list, "A", "B", "C");
Java 9+的工厂方法 Java 9及以上版本提供了简洁的工厂方法:

List<String> list = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B");
Map<String, Integer> map = Map.of("A", 1, "B", 2);
Stream API赋值 使用Stream进行集合赋值和转换:
List<String> list = Stream.of("A", "B", "C").collect(Collectors.toList());
不同类型集合的赋值
List赋值
// 可变List
List<String> mutableList = new ArrayList<>(Arrays.asList("A", "B"));
// 不可变List
List<String> immutableList = List.of("A", "B");
Set赋值

// 可变Set
Set<String> mutableSet = new HashSet<>(Arrays.asList("A", "B"));
// 不可变Set
Set<String> immutableSet = Set.of("A", "B");
Map赋值
// 可变Map
Map<String, Integer> mutableMap = new HashMap<>();
mutableMap.put("A", 1);
mutableMap.put("B", 2);
// 不可变Map
Map<String, Integer> immutableMap = Map.of("A", 1, "B", 2);
集合间的相互赋值
List之间赋值
List<String> source = List.of("A", "B");
List<String> target = new ArrayList<>(source);
Set转List
Set<String> set = Set.of("A", "B");
List<String> list = new ArrayList<>(set);
数组转集合
String[] array = {"A", "B"};
List<String> list = Arrays.asList(array); // 固定大小
List<String> mutableList = new ArrayList<>(Arrays.asList(array)); // 可变
注意事项
- 使用
Arrays.asList()返回的List大小固定,不能添加/删除元素 - Java 9的
List.of()/Set.of()/Map.of()创建的集合不可变 - 集合间的赋值通常是浅拷贝,元素对象本身不会被复制
- 对于自定义对象集合,需要正确实现
equals()和hashCode()方法






