搞懂Collection集合-List集合
学习目标
- 掌握集合提出的背景
- 掌握集合的特点
- 掌握集合的分类
- 掌握集合中的List集合的操作
- 掌握集合的List集合使用场景
1.集合提出的背景
常用的数据结构有:数组,链表,队列,栈,树和散列表等等。在实际程序上除了内置的数组外,Java把其他的数据结构封装起来做成API,这些API被称为集合类。所以,Java中的容器主要分为数组和集合类。
2.集合的特点
- 集合的长度可变,数组的长度固定
- 集合只能存储引用类型(只能存储对象,类似int类型会自动装箱成Integer),数组既可以存储基本数据类型也可以存储引用类型
3.集合的分类
Java中的集合类可以分为两大类:一类是实现Collection接口;另一类是实现Map接口。Collection根据不同的存储需求(元素是否可以重复)分为List和Set,List中的元素允许重复,而Set的元素不允许重复。
4.List集合
4.1 List集合的特点
- 有序存储
- 带有索引,可以通过索引对集合中的元素进行操作
- 元素可重复
4.2 List集合子类
List集合常见的三个子类:
子类 | 底层数据结构 |
---|---|
ArrayList | 数组 |
LinkedList | 链表 |
Vector | 数组 |
4.3 ArrayList
ArrayList集合底层是数组实现的,元素查找快,增删慢,由于实际开发过程中,查询的需求要比增删的需求大,所以,一般都是使用ArrayList,且增数据,往往是从在尾部插入数据。
- ArrayList是基于动态数组实现的,在增删的时候需要数组的拷贝赋值方法:System.arraycopy()
//native:arraycopy是c写的
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
优点:
- 查询元素效率高
缺点:
- 增删元素效率低,时间复杂度高
4.3.1 ArrayList常用方法
介绍构造方法,已经增删改查方法
构造方法
private static final int DEFAULT_CAPACITY = 10;
//有参构造,但是输入是0的时候返回
private static final Object[] EMPTY_ELEMENTDATA = {};
//无参构造,返回
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//数组存储元素
transient Object[] elementData;
private int size;
//有参构造
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
//无参构造
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//<? extends E>:限制泛型上线是E
//传入集合元素进行构造,
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
添加方法
步骤:
- 检查容量是否足够
- 足够:直接添加
- 不足够:先扩容再添加
- 直接添加元素(在尾部)
//直接添加元素
public boolean add(E e) {
//检查
ensureCapacityInternal(size + 1); // Increments modCount!!
//赋值
elementData[size++] = e;
return true;
}
//直接添加元素,调用的方法
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//得到最小容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 判断,然后扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//扩容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
- 指定index添加元素
//指定index添加元素
public void add(int index, E element) {
//检查index是否越界
rangeCheckForAdd(index);
//扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//插入
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
删除方法
- 根据索引删除值
public E remove(int index) {
//检查index是否越界
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
//移动的个数
int numMoved = size - index - 1;
if (numMoved > 0)
//删除元素
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//垃圾回收
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
- 根据内容删除值
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
修改方法
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
查找方法
public E get(int index) {
//检查index是否越界
rangeCheck(index);
//根据索引返回值
return elementData(index);
}
4.4 LinkedList
LinkedList的底层是双向链表,同时实现了List接口和Deque接口。可以像操作队列和栈一样操作LinkedList,但是如果想使用栈或队列数据结构,推荐使用ArrayDeque,相比具有更好的性能。
优点:
- 增删元素效率高,时间复杂度为0(1)
- 可以动态改变集合的大小
缺点:
- 链表不具备良好的空间局部性
4.4.1LinkedList常用方法
构造方法
核心组成元素
- 链表长度
- 头节点
- 尾节点
- 节点元素
节点类
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
添加方法
//添加元素
public boolean add(E e) {
linkLast(e);
return true;
}
//把元素添加到最后
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
删除方法
- 根据索引删除
public E remove(int index) {
//检测index是都越界
checkElementIndex(index);
return unlink(node(index));
}
//删除元素
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
- 根据值删除
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
修改方法
public E set(int index, E element) {
//检测index是否越界
checkElementIndex(index);
//返回指定index的node
Node<E> x = node(index);
//修改
E oldVal = x.item;
x.item = element;
return oldVal;
}
查找方法
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
//返回特定索引的节点
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
4.5 Vector
ArrayList和Vector的关系,类似于HashMap和HashTable,StringBuilder和StringBuffer,后者是前者线程安全版本的实现。Vector只要是关键性的操作,方法前面都加了synchronized关键字,来保证线程的安全性。
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
- 为保证线程安全,多使用Vector
- 查找业务多,多使用ArrayList
ist和Vector的关系,类似于HashMap和HashTable,StringBuilder和StringBuffer,后者是前者线程安全版本的实现。Vector只要是关键性的操作,方法前面都加了synchronized关键字,来保证线程的安全性。
总结
- 为保证线程安全,多使用Vector
- 查找业务多,多使用ArrayList
- 增删业务多,多使用LinkedList
注:仅用于学习交流