Java中的集合框架

1、什么是集合?
(1)用来存储其他对象的对象
(2)数组长度是固定的,集合是可以扩容的
(3)数组要求所有的元素类型是相同的,集合是可以存储不同类型的元素

2、什么是框架?
框架是有类、接口和继承结构的

3、Java的集合框架
集合提供的接口:
Java中的集合框架
Collection接口:Set接口和List接口继承自Collection
Set接口的特点:(集合)
(1)没有次序
(2)元素不允许重复
SortedSet接口:Set接口的子接口
(1)将元素排好序,从大到小
(2)元素不允许重复,不允许元素的值相等
List接口的特点:(列表)
(1)有次序
(2)允许重复

集合提供的接口对应的实现类:
Java中的集合框架

4、ArrayList:底层用数组实现的List
构造方法:
ArrayList()
创建一个长度为10的ArrayList(ArrayList对象会以10的倍数扩容)
ArrayList(Collection c)
用Collection对象构造ArrayList对象
ArrayList(int initialCapacity)
给定一个初始值创建指定长度的ArrayList

方法:
boolean add(E o)
追加元素到list结尾
void add(int index,E element)
将element插入到list的index位置
boolean addAll(Collection c)
将Collection对象c追加到list结尾
boolean addAll(int index,Collection c)
将Collection对象c插入到list的index位置
void clear()
清空list
boolean contains(Object elem)
判断list是否包含elem,包含返回true,否则false
E get(int index)
返回index位置的元素
int indexOf(Object elem)
返回elem在list中第一次出现的下标,没有则返回-1
boolean isEmpty()
判断list是否为空
int lastIndexOf(Object elem)
返回elem在list中最后一次出现的下标,没有则返回-1
E remove(int index)
删除index位置的元素,并返回删除的元素
boolean remove(Object o)
删除list中的元素o,删除成功返回true
protected void removeRange(int fromIndex,int toIndex)
删除fromIndex到toIndex范围内的元素,包括fromIndex位置的元素,不包含toIndex位置的元素
E set(int index, E elem)
将index位置的元素设置为elem,并返回原来的元素
int size()
返回list的长度
Object[] toArray()
将list当成数组返回

5、LinkedList:底层使用链表实现List
LinkedList和ArrayList实现的方法大致是相同的
构造方法:
LinkedList()
构造一个空的List
LinkedList(Collection c)
使用一个已存在的Collection对象构造一个List

方法:
boolean add(E o)
void clear()
boolean contains(Object obj)
E get(int index)
int indexOf(Object obj)
E remove()
删除List的第一个元素
E remove(int index)
boolean remove(Object obj)
E set(int index, E element)
int size()
Object[] toArray()
E getFirst()
返回List的第一个元素
E getLast()
返回List的最后一位元素

ArrayList和LinkedList的使用场景:
(1)数组的使用场景:访问效率高,插入删除效率低,自动扩容效率低
(2)链表的使用场景:访问效率低,插入删除效率高,自动扩容效率高

6、Vector:和ArrayList的实现方法是一样的,底层也是用数组实现的
Vector和ArrayList的区别是,Vector是线程安全的,任意时候只有一个线程访问和修改Vector对象。其包含的方法和ArrayList相同