Collection.png

Collection 接口

Collection 接口方法

接口声明 描述
int size(); 返回集合有多少个元素
boolean isEmpty(); 返回集合是否为空
boolean contains(Object o); 返回集合是否包含 o 元素
boolean add(E e); 给集合新增元素 e
boolean remove(Object o); 删除集合中的 o 元素
boolean containsAll(Collection<?> c); 判断集合是否包含集合 c 中的元素
boolean addAll(Collection<? extends E> c); 向集合中新增集合 c 中的元素
boolean removeAll(Collection<?> c); 删除集合中与集合 c 中相同的元素
Object[] toArray(); 将集合转成数组

遍历

Iterator-迭代器

  1. public interface Collection<E> extends Iterable<E> {
  2. /**
  3. * Returns an iterator over the elements in this collection. There are no
  4. * guarantees concerning the order in which the elements are returned
  5. * (unless this collection is an instance of some class that provides a
  6. * guarantee).
  7. *
  8. * @return an <tt>Iterator</tt> over the elements in this collection
  9. */
  10. Iterator<E> iterator();

Collection 接口由于继承了 Iterable,所以继承有一个获取迭代器的方法。
迭代器主要有两个方法配合使用来遍历 Collection 集合元素:

方法声明 方法描述
boolean hasNext(); 判断集合中是否还有下一个元素;
E next(); 取出集合中的下一个元素;
Collection<String> list = new ArrayList<>();
// 添加元素略
Iterator iterator = list.iterator();
while (iterator.hasNext) {
    System.out.println(iterator.next());
}

增强 for

增强 for 实际上底层也是使用 Iterator-迭代器 实现的遍历。相当于简化版的迭代器遍历

Collection<String> list = new ArrayList<>();
// 添加元素略
for (String str : list) {
    System.out.println(str);
}

List 接口

List 接口特点

  • List 集合中的元素添加顺序和取出顺序是一致的,存储元素允许重复;
  • List 集合中每个元素都有其对应的顺序索引,索引从 0 开始,如获取第一个元素 get(0);

    List 接口方法

    除了继承自 Collection 的方法外,还有以下常用方法:
方法声明 描述
void add(int index, E element); 在 index 位置添加 element 元素
boolean addAll(int index, Collection<? extends E> c); 从 index 位置开始添加集合 c 中的所有元素
int indexOf(Object o); 返回元素 o 首次在集合中出现的位置
int lastIndexOf(Object o); 返回元素 o 最后在集合中出现的位置
E remove(int index); 删除 index 索引的元素并返回该元素
E get(int index); 返回 index 位置的元素
E set(int index, E element); 替换 index 位置的元素为 element
List subList(int fromIndex, int toIndex); 返回从 fromIndex 到 toIndex 的子集合(前闭后开)

迭代器

List 除了使用 Collection 继承的 Iterator 迭代器外,还有一个 ListIterator 迭代器。该迭代器拥有针对于 List 的额外方法:

方法声明 方法描述
boolean hasNext(); 判断集合中是否还有下一个元素
E next(); 取出集合中的下一个元素
boolean hasPrevious(); 判断集合中是否有上一个元素
E previous(); 返回上一个元素
int nextIndex(); 返回下一个元素的索引
int previousIndex(); 返回上一个元素的索引

Set 接口

Set 接口特点

  • 添加元素跟取出元素的顺序不一致,但顺序是固定的,没有索引;
  • 不允许包含重复的元素,最多有一个 null;

    Set 接口方法

    to Collection 接口方法

Set 接口的方法都继承自 Collection 接口,没有自己定义的其他方法。

迭代器

可以使用继承自 Collection 接口的 Iterator 迭代器,和迭代器的简写形式:增强 for 循环;

补充:Queue 接口

Queue 接口特点

  • 队列,先进先出,FIFO
  • Queue 接口与 List、Set 同一级别,都是继承了 Collection 接口。LinkedList 实现了 Deque 接口。

    Queue 接口方法

    add() 方法继承自 Collection 接口
方法声明 方法描述
boolean add(E e); 增加一个元素,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
boolean offer(E e); 添加一个元素并返回true,如果队列已满,则返回false
E remove(); 移除并返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
E poll(); 移除并返问队列头部的元素,如果队列为空,则返回null
E element(); 返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
E peek(); 返回队列头部的元素,如果队列为空,则返回null