Java集合位于java.util.*,平时使用得非常多,当其中与泛型(参见前面)结合起来时,刚开始理解起来会比较费力,所以读了一下集合框架和源码。
Java集合框架如下(图片来源于http://www.cnblogs.com/skywang12345/p/3308498.html):
其中虚线框内全部为接口(其中也标有接口),蓝色字体为抽象类。
其中Collection接口为所有集合的父类。源码如下(jdk为1.7,加上了迭代器):
public interface Collection<E> extends Iterable<E> {//继承迭代器接口,每个集合类须实现其中的方法,允许使用迭代器来遍历
int size();//元素个数
boolean isEmpty();//不包含元素,则为true
boolean contains(Object o);//是否包含某元素
Iterator<E> iterator(); //Iterable接口里的方法,迭代器接口
Object[] toArray(); //转化为数组
<T> T[] toArray(T[] a); //转换为数组,具体的类型
boolean add(E e); //增加元素
boolean remove(Object o);//移除元素
boolean containsAll(Collection<?> c);//是否包含另外一个集合
boolean addAll(Collection<? extends E> c);//增加所有元素
boolean removeAll(Collection<?> c);//移除此集合中所有元素
boolean retainAll(Collection<?> c);//仅保留这个集合重的元素
void clear();//清空
boolean equals(Object o);//重写equals方法
int hashCode();//重写hashcode方法
}
public interface Iterable<T> {//迭代器接口
Iterator<T> iterator();//迭代器
}
public interface Iterator<E> {//迭代器类
boolean hasNext();//如果仍有元素可以迭代,则返回 true
E next();//返回迭代的下一个元素。
void remove();//删除元素
}
public interface ListIterator<E> extends Iterator<E> {//双向迭代器
boolean hasNext();
E next();
boolean hasPrevious();//如果以逆向遍历列表,列表迭代器有多个元素,则返回 true
E previous();//返回列表中的前一个元素
int nextIndex();//返回对 next的后续调用所返回元素的索引
int previousIndex();//返回对 previous的后续调用所返回元素的索引
void remove();//移除
void set(E e);//修改当前元素
void add(E e);//将指定的元素插入列表
}