一、List集合
特点: List集合代表一个元素有序、可重复的集合,集合中每个元素都有其对应的顺序索引。
1、ArrayList集合
ArrayList类封装了一个动态的、允许再分配的Object[]数组。
1.1、常用方法
void add(Object obj) 向List集合中添加元素,元素可以重复添加,元素值可以是null
int size() 获取List集合中元素的个数
Object get(int index) 从List集合中获取元素
boolean remove(Object obj) 从List集合中删除元素
boolean remove(int index) 从List集合中删除元素
void clear() 从List集合中删除所有元素
boolean contains(Object obj) 集合中是否存在某个元素,如果存在返回true
2、Vector集合
特点:Vector和ArrayList使用方法基本一致, Vector是一个线程安全的List实现类,但ArrayList是线程不安全的实现类,所以Vector要比ArrayList的安全性高一些,但是ArrayList的性能要比Vector高一些。
ps:在多线程的开发情况下,选择Vector,否则其他情况都使用ArrayList。
3、LinkedList集合
特点:LinkedList是通过双向链表去实现的,它不存在容量不足的问题,适合删除操作,因为是链表。
LinkedList<Integer> array = new LinkedList<Integer>();
3.1、常用方法
基本方法同ArrayList,同时增加了一些方法。所以在实例化时,不能使用多态实例化,否则调用不到方法。
array.addFirst(e); 在集合最前面添加元素
array.addLast(e); 在集合最后面添加元素
array.getFirst(e); 获取集合最前面添加元素
array.getLast(e); 获取集合最后面添加元素
array.removeFirst(e); 删除集合最前面添加元素
array.removeLast(e); 删除集合最后面添加元素
4、封装类
在list集合中,需要填写数据类型的封装类,如:
LinkedList<Integer> arrayOld = new LinkedList<Integer>(); //需要用int的封装类Integer