java基础-集合接口(Collection)

Collection 接口概述

Collection 接口是 Java 集合框架中最基本的接口,它定义了所有集合类都应该具备的基本操作。

主要方法

1. 添加元素

java 复制代码
boolean add(E e);           // 添加单个元素
boolean addAll(Collection<? extends E> c); // 添加集合中的所有元素

2. 删除元素

java 复制代码
boolean remove(Object o);    // 删除单个元素
boolean removeAll(Collection<?> c); // 删除集合中的所有元素
boolean retainAll(Collection<?> c); // 仅保留指定集合中的元素
void clear();               // 清空集合

3. 查询操作

java 复制代码
int size();                 // 返回元素个数
boolean isEmpty();          // 判断是否为空
boolean contains(Object o); // 判断是否包含元素
boolean containsAll(Collection<?> c); // 判断是否包含集合所有元素

4. 集合转换

java 复制代码
Object[] toArray();         // 转换为数组
<T> T[] toArray(T[] a);     // 转换为指定类型的数组

5. 迭代器

java 复制代码
Iterator<E> iterator();     // 返回迭代器

Collection 接口的主要实现类

java 复制代码
// List 接口 - 有序集合
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
List<String> vector = new Vector<>();

// Set 接口 - 不重复集合
Set<String> hashSet = new HashSet<>();
Set<String> linkedHashSet = new LinkedHashSet<>();
Set<String> treeSet = new TreeSet<>();

// Queue 接口 - 队列
Queue<String> priorityQueue = new PriorityQueue<>();
Queue<String> arrayDeque = new ArrayDeque<>();

实际使用示例

基本操作示例

java 复制代码
import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        // 创建集合
        Collection<String> collection = new ArrayList<>();
        
        // 添加元素
        collection.add("Apple");
        collection.add("Banana");
        collection.add("Orange");
        collection.addAll(Arrays.asList("Grape", "Mango"));
        
        System.out.println("集合元素: " + collection);
        System.out.println("集合大小: " + collection.size());
        System.out.println("是否包含Apple: " + collection.contains("Apple"));
        
        // 删除元素
        collection.remove("Banana");
        System.out.println("删除Banana后: " + collection);
        
        // 遍历集合
        System.out.println("遍历集合:");
        for (String fruit : collection) {
            System.out.println(fruit);
        }
        
        // 使用迭代器
        System.out.println("使用迭代器:");
        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

集合运算示例

java 复制代码
public class CollectionOperations {
    public static void main(String[] args) {
        Collection<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Collection<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));
        
        // 并集
        Collection<Integer> union = new HashSet<>(set1);
        union.addAll(set2);
        System.out.println("并集: " + union);
        
        // 交集
        Collection<Integer> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);
        System.out.println("交集: " + intersection);
        
        // 差集
        Collection<Integer> difference = new HashSet<>(set1);
        difference.removeAll(set2);
        System.out.println("差集: " + difference);
    }
}

Java 8 新增的默认方法

Java 8 为 Collection 接口添加了一些有用的默认方法:

java 复制代码
public class CollectionJava8Example {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>(
            Arrays.asList("Java", "Python", "C++", "JavaScript", "Go")
        );
        
        // removeIf - 根据条件删除元素
        collection.removeIf(s -> s.length() > 4);
        System.out.println("删除长度>4的元素后: " + collection);
        
        // stream - 转换为流
        long count = collection.stream()
                              .filter(s -> s.startsWith("J"))
                              .count();
        System.out.println("以J开头的元素个数: " + count);
        
        // forEach - 遍历操作
        System.out.println("forEach遍历:");
        collection.forEach(System.out::println);
        
        // spliterator - 可分割迭代器
        Spliterator<String> spliterator = collection.spliterator();
        spliterator.forEachRemaining(System.out::println);
    }
}

集合的批量操作

java 复制代码
public class BulkOperations {
    public static void main(String[] args) {
        Collection<String> source = Arrays.asList("A", "B", "C", "D", "E");
        Collection<String> target = new ArrayList<>();
        
        // 批量添加
        target.addAll(source);
        System.out.println("批量添加后: " + target);
        
        // 批量删除
        target.removeAll(Arrays.asList("A", "C"));
        System.out.println("批量删除后: " + target);
        
        // 批量保留
        target.retainAll(Arrays.asList("B", "D", "F"));
        System.out.println("批量保留后: " + target);
        
        // 判断包含关系
        System.out.println("是否包含所有元素: " + 
            target.containsAll(Arrays.asList("B", "D")));
    }
}

重要特性

  1. 泛型支持 - 提供类型安全

  2. 自动装箱 - 基本类型自动转换为包装类

  3. Fail-Fast 迭代器 - 并发修改时快速失败

  4. 可序列化 - 支持对象序列化

  5. 可克隆 - 支持对象克隆

使用建议

  1. 根据需求选择合适的集合实现

  2. 使用泛型确保类型安全

  3. 注意集合的线程安全性

  4. 合理使用批量操作提高性能

  5. 利用 Java 8 的流式操作处理集合数据

Collection 接口为所有集合类提供了统一的操作方式,是理解和使用 Java 集合框架的基础。

相关推荐
yujunl4 分钟前
U9 BE插件的调试
开发语言
青山木6 分钟前
Hot 100 --- 打家劫舍
java·数据结构·算法·leetcode·动态规划
敲代码的嘎仔10 分钟前
28届后端开发-百人小厂面试题
java·后端·面试·程序员·秋招·实习·转正
牛油果子哥q11 分钟前
多模态大模型工程入门:图文Embedding、图文RAG、图片解析、C++多模态接口封装实战
开发语言·c++·embedding
Bs_MoneyMagnet16 分钟前
基于springboot+vue的爱心众筹系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·管理系统
AIFQuant19 分钟前
Python股票实时价格告警系统:WebSocket订阅与REST快照实战
开发语言·python·websocket·a股行情
wuyk55529 分钟前
从零吃透 MQTT 通信|第 10 章 阿里云 / 腾讯云 MQTT 设备完整对接实战,三元组、签名、设备上云调试
c语言·开发语言·stm32·学习·阿里云·云计算·腾讯云
名字还没想好☜30 分钟前
Java Collectors.groupingBy 进阶:多级分组、下游收集器与统计聚合一次搞定
java·windows·后端·python·spring
Wang's Blog34 分钟前
Java框架快速入门: Spring Security+OAuth2之前端按钮级安全与路由守卫
java·安全·spring
ocean21031 小时前
2025-2026年Java语言及生态面试高频知识点洞察
java·开发语言·面试