224. Java 集合 - 使用 Collection 接口存储元素
1. 🚪 集合接口(Collection Interface)的入口
在 Java 的集合框架中,除了Map之外,其他所有接口 都是在处理存储元素到容器中 的问题。 而**List和 Set**这两个重要接口,共同继承了Collection接口 ,它们的基本行为都是由Collection统一建模的。
2. 🧰 Collection接口能做什么?
在不涉及过多技术细节的情况下,Collection接口提供了一组通用操作,包括:
🔹 基本容器操作
- 添加 元素(
add()) - 删除 元素(
remove()) - 检查 某个元素是否存在(
contains()) - 获取 容器中元素的数量(
size()) - 检查 集合是否为空(
isEmpty()) - 清空 集合(
clear())
🔹 集合操作
因为集合本身是"元素的合集",所以也支持一些"集合论"相关的操作,比如:
- 包含检查 (
containsAll()):判断一个集合是否包含另一个集合的所有元素 - 并集 (
addAll()):把另一个集合的元素加入当前集合 - 交集 (
retainAll()):只保留当前集合和指定集合共有的元素 - 差集 (
removeAll()):移除当前集合中出现在指定集合里的元素
🔹 访问元素的方式
- 使用 Iterator 遍历 元素(
iterator()) - 通过 Stream 流式处理 元素(
stream(),可以并行parallelStream())
3. 🌟 例子:Collection基本操作演示
java
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
Collection<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Fruits: " + fruits);
System.out.println("Contains 'Banana'? " + fruits.contains("Banana"));
System.out.println("Size: " + fruits.size());
fruits.remove("Apple");
System.out.println("After removing 'Apple': " + fruits);
Collection<String> tropicalFruits = List.of("Banana", "Mango");
System.out.println("Fruits contains all tropical fruits? " + fruits.containsAll(tropicalFruits));
fruits.addAll(tropicalFruits);
System.out.println("After adding tropical fruits: " + fruits);
fruits.retainAll(List.of("Banana"));
System.out.println("After retaining only 'Banana': " + fruits);
fruits.clear();
System.out.println("Is collection empty after clear()? " + fruits.isEmpty());
}
}
运行输出:
java
Fruits: [Apple, Banana, Orange]
Contains 'Banana'? true
Size: 3
After removing 'Apple': [Banana, Orange]
Fruits contains all tropical fruits? false
After adding tropical fruits: [Banana, Orange, Banana, Mango]
After retaining only 'Banana': [Banana, Banana]
Is collection empty after clear()? true
🎯 小总结:
Collection接口是各种集合容器的统一标准。List和Set等更具体的集合,继承了这些基本操作,但各自有额外特性。
4. ❓ 那么,Collection、List 和 Set 到底有什么区别?
虽然 List 和 Set 都是 Collection,但是:
| 特性 | Collection | List | Set |
|---|---|---|---|
| 是否有序? | 不一定 | 有序(按插入顺序或自定义排序) | 无序(有些实现可以有顺序,如LinkedHashSet) |
| 是否允许重复? | 不确定 | 允许重复元素 | 不允许重复元素 |
| 如何访问? | 迭代或流 | 通过索引(get(index)) |
通过迭代 |
📌 举个例子:
- 想存放一组可以重复的、顺序重要的东西?➡️用 List
- 想存放一组无重复的、只关心存在与否的东西?➡️用 Set
5. 🌊 示例:使用Stream流式处理Collection
java
import java.util.*;
public class StreamExample {
public static void main(String[] args) {
Collection<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println); // 打印偶数
}
}
输出:
java
2
4
6
🎯 这里用到了 stream(),可以更灵活地处理集合里的元素!