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)