Java集合——Collection

在Java中,Collection 是集合框架的根接口,定义了集合类应遵循的基本方法。以下是 Collection 接口的一些重要知识点。

1. 核心方法

  • add(E e):将元素 e 添加到集合中。
  • remove(Object o):从集合中移除指定的元素 o
  • size():返回集合中的元素数量。
  • isEmpty():检查集合是否为空。
  • clear():移除集合中的所有元素。
  • contains(Object o):检查集合是否包含指定的元素 o
  • iterator():返回集合的迭代器,用于遍历集合。

2. 实现类

  • ArrayList:实现了 List 接口,提供动态数组的功能。
  • LinkedList:实现了 ListDeque 接口,提供双向链表的功能。
  • HashSet:实现了 Set 接口,底层使用哈希表存储元素,不保证元素顺序。
  • TreeSet:实现了 Set 接口,底层使用红黑树,元素有序。

3. 集合操作

  • 添加元素:使用 add 方法。
  • 删除元素:使用 remove 方法。
  • 检查包含:使用 contains 方法。
  • 清空集合:使用 clear 方法。

4. 遍历集合

  • 使用迭代器

Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
    E element = iterator.next();
    // 处理元素
}
  • 增强的 for 循环

for (E element : collection) {
    // 处理元素
}

5. 实用工具

  • Collections:提供了静态方法来操作集合,如排序、反转等。
Collections.sort(list);
Collections.reverse(list);

你可能感兴趣的:(Java集合,java,开发语言)