集合之单值集合

Collection

Collection接口是Java类集中保存单值的最大父接口。
接口定义如下:

public interface Collection<E> extends Iterable<E>

常用方法如下:

方法名称描述
public boolean add(E e)向集合中插入一个元素
public boolean addAll(Collection<? extends E> c)向集合中插入一组元素
public boolean contains(Object o)查找一个元素是否存在
public boolean containsAll(Collection<?> c)查找一组元素是否存在
public boolean isEmpty()判断集合是否为空
public Iterator iterator()为Iterator接口实例化
public boolean remove()从集合中删除一个对象
public boolean removeAll(Collection<?> c)从集合中删除一组对象
public boolean retainAll(Collection<?> c)判断是否没有指定的集合
public int size()求出集合中元素的个数
public Object[] toArray()以对象数组的形式返回集合中的全部内容
public T[] toArray(T[] a)指定操作的泛型类型,并把内容返回
public boolean equals(Object o)从Object类中覆写而来
public int hashCode()从Object类中覆写而来

List

List是Collection的子接口,元素允许重复,存储的数据是有顺序的
List子接口定义:

public interface List<E> extends Collection<E>

常用方法如下:

方法名称描述
public void add(int index,E element)指定位置处添加
public boolean addAll(int index,Collection<? extends E> c)在指定位置处添加一组元素
public E get(int index)根据索引位置取出一个元素
public int indexOf(Object o)根据对象查找指定的位置,找不到返回-1
public int lastIndexOf(Object o)从后面向前查找位置,找不到返回-1
public ListIterator listIterator()返回ListIterator接口的实例
public ListIterator listIterator(int index,E element)返回从指定位置的ListIterator接口的实例
public E remove(int index)删除指定位置的内容
public E set(int index,E element)修改指定位置的内容
public List subList(int fromIndex,int toIndex)返回子集合

ArrayList

基于动态数组实现,初始化时默认构造方法会创建一个空数组
在这里插入图片描述
当ArrayList第一次添加元素时,扩充容量为10
在这里插入图片描述
之后需要扩容时会扩容原数组的1.5倍
在这里插入图片描述

Vector

Vector也是采用动态数组实现的,不过它默认初始化时会创建一个容量为10的数组
在这里插入图片描述
当Vector需要扩容时,如果增量为0则扩容为原来的两倍,大于0则根据增量扩容
在这里插入图片描述
在Vector创建时可以设置增量
在这里插入图片描述
除此之外,Vector还是线程安全的

LinkedList

LinkedList使用的是双向链表结构
LinkedList提供了用作栈和队列的方法
在这里插入图片描述

Set

Set是Collection的子接口,元素不允许重复

HashSet

HashSet是基于HashMap实现的,是散列存储的,不能保证存储的顺序
在这里插入图片描述
当添加是只是使用了HashMap的键,值则是存的固定值
在这里插入图片描述

TreeSet

TreeSet采用二叉树存储,内部是基于TreeMap实现的,存储是有序的
使用TreeSet存储的对象需要实现Comparable接口