在 Java 中,Collection
是集合框架的根接口之一,它定义了一组对象的基本操作。Collection
接口位于java.util
包下,是所有单列集合的父接口,主要派生了两个子接口:List
(有序可重复)和 **Set
**(无序不可重复)。以下是关于Collection
集合的详细介绍:
1. Collection
接口的基本方法
Collection
接口定义了集合操作的核心方法,所有实现类都必须实现这些方法:
java
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>(); // 使用ArrayList实现
// 添加元素
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
System.out.println(collection); // [Apple, Banana, Cherry]
// 检查元素是否存在
boolean containsApple = collection.contains("Apple"); // true
// 删除元素
collection.remove("Banana");
System.out.println(collection); // [Apple, Cherry]
// 集合大小
int size = collection.size(); // 2
// 判断集合是否为空
boolean isEmpty = collection.isEmpty(); // false
// 转换为数组
Object[] array = collection.toArray();
// 清空集合
collection.clear();
System.out.println(collection); // []
}
}
2. Collection
的主要子接口
List
接口
有序可重复的集合,支持索引访问。常见实现类:
ArrayList
:动态数组实现,随机访问效率高。LinkedList
:双向链表实现,插入和删除效率高。Vector
:线程安全的动态数组(已过时,推荐使用Collections.synchronizedList
)。
java
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add(1, "C"); // 在索引1处插入
System.out.println(list.get(0)); // A
Set
接口
无序不可重复的集合。常见实现类:
HashSet
:基于哈希表实现,不保证元素顺序。LinkedHashSet
:继承自HashSet
,维护插入顺序。TreeSet
:基于红黑树实现,元素按自然顺序或指定比较器排序。
java
Set<Integer> set = new HashSet<>();
set.add(3);
set.add(1);
set.add(2);
System.out.println(set); // [1, 2, 3](顺序不保证)
Queue
接口
队列接口,遵循 FIFO(先进先出)原则。常见实现类:
LinkedList
:双向队列实现。PriorityQueue
:优先队列,元素按优先级排序。
java
Queue<String> queue = new LinkedList<>();
queue.offer("A"); // 入队
queue.offer("B");
String head = queue.poll(); // 出队,返回A
3. Collection
的遍历方式
迭代器(Iterator)
java
Collection<String> collection = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("B")) {
iterator.remove(); // 安全删除元素
}
}
增强 for 循环
java
for (String element : collection) {
System.out.println(element);
}
Lambda 表达式(Java 8+)
java
collection.forEach(element -> System.out.println(element));
// 或使用方法引用
collection.forEach(System.out::println);
4. 集合工具类:Collections
java.util.Collections
类提供了一系列静态方法,用于操作集合:
java
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1));
// 排序
Collections.sort(numbers); // [1, 3, 5, 8]
// 反转
Collections.reverse(numbers); // [8, 5, 3, 1]
// 查找最大值和最小值
int max = Collections.max(numbers); // 8
int min = Collections.min(numbers); // 1
// 线程安全包装
List<Integer> synchronizedList = Collections.synchronizedList(numbers);
5. 集合与数组的转换
java
// 数组转集合
String[] array = {"A", "B", "C"};
List<String> list = Arrays.asList(array); // 固定大小的列表
// 集合转数组
Collection<String> collection = new ArrayList<>(list);
String[] newArray = collection.toArray(new String[0]); // 指定类型
6. 集合的注意事项
-
泛型的使用:始终指定泛型类型,避免原始类型(raw type)。
java
// 推荐 List<String> list = new ArrayList<>(); // 不推荐(原始类型,可能导致ClassCastException) List rawList = new ArrayList();
-
线程安全:
- 大多数集合类(如
ArrayList
、HashMap
)是非线程安全的。 - 如需线程安全,可使用
Collections.synchronizedList()
或ConcurrentHashMap
。
- 大多数集合类(如
-
快速失败(Fail-Fast)机制:
- 当使用迭代器遍历集合时,若集合结构被修改(如添加、删除元素),会抛出
ConcurrentModificationException
。 - 解决方法:使用
Iterator.remove()
或并发集合(如CopyOnWriteArrayList
)。
- 当使用迭代器遍历集合时,若集合结构被修改(如添加、删除元素),会抛出
示例代码:集合操作综合应用
java
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
// 创建集合
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// 遍历集合
System.out.println("遍历方式1:增强for循环");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 使用Stream过滤
System.out.println("\n遍历方式2:Stream + Lambda");
fruits.stream()
.filter(fruit -> fruit.startsWith("A"))
.forEach(System.out::println);
// 集合转数组
String[] fruitArray = fruits.toArray(new String[0]);
System.out.println("\n数组内容:" + Arrays.toString(fruitArray));
// 使用Collections工具类
Collections.sort(fruits);
System.out.println("\n排序后:" + fruits);
// 使用Set去重
Set<String> uniqueFruits = new HashSet<>(fruits);
System.out.println("去重后:" + uniqueFruits);
}
}
总结
Collection
接口是 Java 集合框架的基础,通过其子接口(List
、Set
、Queue
)和实现类(如ArrayList
、HashSet
),提供了丰富的集合操作功能。合理使用泛型、迭代器和工具类,可以高效地处理各种数据集合。