Collection 接口是 Java 集合框架中的顶层接口,它定义了一组通用的方法和行为,用于操作和管理一组对象。
一、 Collection 接口常用方法:
1. 添加元素的方法:
- boolean add(E element): 将指定的元素添加到集合中,如果成功添加则返回 true。
- boolean addAll(Collection<? extends E> collection): 将另一个集合中的所有元素添加到当前集合中,如果成功添加任意一个元素,则返回 true。
2. 删除元素的方法:
- boolean remove(Object object): 从集合中删除指定的元素,如果删除成功则返回 true。
- boolean removeAll(Collection<?> collection): 删除集合中与指定集合中相同的所有元素,如果集合发生改变则返回 true。
- void clear(): 清空集合中的所有元素,使其为空集合。
3. 判断包含关系的方法:
- boolean contains(Object object): 判断集合是否包含指定的元素,如果包含则返回 true。
- boolean containsAll(Collection<?> collection): 判断当前集合是否包含另一个集合中的所有元素,如果包含则返回 true。
- boolean isEmpty(): 判断集合是否为空,如果为空则返回 true。
4. 获取集合信息的方法:
- int size(): 返回集合中的元素个数。
- Object[] toArray(): 将集合转换为数组,返回包含所有元素的数组。
- Iterator<E> iterator(): 返回一个用于遍历集合中元素的迭代器。
二、Collection 遍历方式
1.迭代器遍历
迭代器是设计用来遍历集合的标准方式。通过调用集合的 iterator()
方法获取一个迭代器对象,然后使用迭代器的 hasNext()
和 next()
方法遍历集合。
Collection<String> collection = new ArrayList<>();
collection.add("apple");
collection.add("banana");
collection.add("orange");
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
2.增强for 循环
增强型 for 循环提供了一种简洁、可读性高的方式来遍历集合。它适用于对集合中的每个元素执行相同的操作。
Collection<String> collection = new ArrayList<>();
collection.add("apple");
collection.add("banana");
collection.add("orange");
for (String element : collection) {
System.out.println(element);
}
在增强型 for 循环中,不能修改集合的结构,否则会导致并发修改异常。如果需要在遍历过程中删除元素,应该使用迭代器。
3.使用 forEach() 方法(Java 8+):
在 Java 8 中,Collection 接口新增了 forEach()
方法,可以直接对集合进行遍历,并提供一个 lambda 表达式用于处理每个元素。
Collection<String> collection = new ArrayList<>();
collection.add("apple");
collection.add("banana");
collection.add("orange");
collection.forEach(element -> {
System.out.println(element);
});
这种方式与使用增强型 for 循环类似,但提供了更灵活的操作方式。
4.使用 Stream API(Java 8+):
Java 8 引入的 Stream API 提供了一种函数式编程的方式来处理集合数据。可以将 Collection 转换为 Stream 对象,然后使用 Stream 的 forEach()
方法遍历集合。
Collection<String> collection = new ArrayList<>();
collection.add("apple");
collection.add("banana");
collection.add("orange");
collection.stream().forEach(element -> {
System.out.println(element);
});