9.1 Java集合框架

1 把集合接口和实现分离

队列接口

public interface Queue<E> // a simplified form of the interface in the standard library
{
    void add(E element);
    E remove();
    int size();
}

循环数组实现队列

public class CircularArrayQueue<E> implements Queue<E> // not an actual library class
{
    private int head;
    private int tail;
    CircularArrayQueue(int capacity) { . . . }
    public void add(E element) { . . . }
    public E remove() { . . . }
    public int size() { . . . }
    private E[] elements;
}

链表实现队列

public class LinkedListQueue<E> implements Queue<E> // not an actual library class
{
    private Link head;
    private Link tail;
    LinkedListQueue() { . . . }
    public void add(E element) { . . . }
    public E remove() { . . . }
    public int size() { . . . }
}

2 集合接口

public interface Collection<E>
{
    boolean add(E element);//用于添加元素,改变集合就返回true,没改变就返回false
    Iterator<E> iterator();//返回迭代器接口,用于遍历每一个元素
    . . .
}

3 迭代器

public interface Iterator<E>
{
    E next();
    boolean hasNext();
    void remove();
    default void forEachRemaining(Consumer<? super E> action);
}

这样使用迭代器

Collection<String> c = . . .;
Iterator<String> iter = c.iterator();
while (iter.hasNext())
{
    String element = iter.next();
    do something with element
}

迭代器支持foreach语法

for (String element : c)
{
    do something with element
}

更简便的是用Lambda表达式

iterator.forEachRemaining(element -> do something with element);

迭代器像是一个游标,next方法就是把这个游标移向下一位然后返回跳过的元素,remove方法是删除刚刚跳过的元素。
注意:remove方法只是删除刚越过的元素,删除过后,就没有刚越过的元素了,再次调用remove会出错的。


4 集合的其他方法

int size()
boolean isEmpty()
boolean contains(Object obj)
boolean containsAll(Collection<?> c)
boolean equals(Object other)
boolean addAll(Collection<? extends E> from)
boolean remove(Object obj)
boolean removeAll(Collection<?> c)
void clear()
boolean retainAll(Collection<?> c)
Object[] toArray()
<T> T[] toArray(T[] arrayToFill)

5 集合框架中的接口

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值