List
List是一个集合,按照元素插入的先后顺序进行排列。
Java集合中List接口的实现类主要有ArrayList、Vector、LinkedList。
ArrayList:底层数据结构是数组,查询快,增删慢,线程不安全,效率高
Vector:底层数据结构是数组,查询快,增删慢, 线程安全, 效率低
LinkedList:底层数据结构是链表,查询慢,增删快, 线程不安全, 效率高
ArrayList
ArrayList的底层是数组,当空间不足的时候,会进行动态扩容。
数组的好处就是随机存储块,但是插入和删除效率不高,删除需要搬运元素,插入有的时候需要动态扩容。
ArrayList是线程不安全的,没有加锁,会出现线程不安全问题
注:ArrayList使用的是1.5倍扩容,并且vector的方法实现了线程安全,但是ArrayLust没有,所以在不要求线程安全的情况下使用ArrayList,能加快代码的运行速度。
import java.util.Arrays;
public class ArrayList {
private Object[] objs;
private int size;
private int capacity = 10;
public ArrayList() {
this.objs = new Object[this.capacity];
}
public ArrayList(int capacity) {
this.capacity = capacity;
this.objs = new Object[this.capacity];
}
//添加一个元素
public void add(Object obj) {
// 如果满了就扩容
if (this.isFull()) {
this.grow();
}
this.objs[size++] = obj;
}
//判断是否满了
private boolean isFull() {
return this.size == this.capacity;
}
//扩容
private void grow() {
// 扩 1.5 倍
int newCapaCity = this.capacity + (this.capacity >> 1);
this.objs = Arrays.copyOf(this.objs, newCapaCity);
this.capacity = newCapaCity;
}
//在指定位置添加元素
public void add(int index, Object obj) {
if (this.isFull()) {
this.grow();
}
for (int i = size; i > index ; i--) {
this.objs[i] = this.objs[i - 1];
}
this.objs[index] = obj;
this.size++;
}
//删除指定位置的元素
public void remove(int index) {
for (int i = index; i < this.size - 1; i++) {
this.objs[index] = this.objs[index + 1];
}
this.size--;
}
//删除指定元素
public void remove(Object obj) {
int index = 0;
for (int i = 0; i < this.size; i++){
if (objs[i] == obj){
index = i;
}else {
throw new RuntimeException("没有该元素");
}
}
remove(index);
}
//替换指定位置的元素
public void update(int index, Object obj) {
this.objs[index] = obj;
}
//获取指定位置的元素
public Object get(int index) {
if (index < size) {
return null;
}