java容器如何创建
Java 容器创建方法
Java 中的容器(集合框架)主要包括 List、Set、Map 等接口及其实现类。以下是常见容器的创建方式。
List 的创建
ArrayList 和 LinkedList 是 List 接口的常用实现类。
// 创建 ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("Java");
arrayList.add("Python");
// 创建 LinkedList
List<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
Set 的创建
HashSet、LinkedHashSet 和 TreeSet 是 Set 接口的常用实现类。
// 创建 HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
// 创建 TreeSet
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(10);
treeSet.add(20);
Map 的创建
HashMap、LinkedHashMap 和 TreeMap 是 Map 接口的常用实现类。
// 创建 HashMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("One", 1);
hashMap.put("Two", 2);
// 创建 TreeMap
Map<String, String> treeMap = new TreeMap<>();
treeMap.put("A", "Apple");
treeMap.put("B", "Banana");
使用工厂方法创建不可变容器
Java 9 引入了 List.of()、Set.of() 和 Map.of() 等工厂方法创建不可变容器。
// 创建不可变 List
List<String> immutableList = List.of("A", "B", "C");
// 创建不可变 Set
Set<Integer> immutableSet = Set.of(1, 2, 3);
// 创建不可变 Map
Map<String, Integer> immutableMap = Map.of("One", 1, "Two", 2);
使用 Arrays.asList 创建 List
Arrays.asList 可以快速创建固定大小的列表,但注意返回的列表不支持添加或删除操作。

List<String> fixedList = Arrays.asList("A", "B", "C");
注意事项
- 不可变容器(如
List.of创建的容器)不允许修改,调用add或remove方法会抛出UnsupportedOperationException。 Arrays.asList返回的列表基于数组,长度固定,修改元素可以,但增删操作会报错。- 选择容器实现类时需根据需求考虑性能特性,如
ArrayList适合随机访问,LinkedList适合频繁插入删除。






