首先我们得了解集合框架的作用
- 让数据在内存中,高效储存、操作而提供的一套用于储存重要数据的API
- 数据在内存中如何定义
- 多数据的储存和操作
- 传统数组(长度固定不便于频繁增删,只提供下标访问而不提供其他操作)的缺点
- 集合框架是基于经典的数据结构,给出不同的多数据储存方式的实现,并给出该结构的最佳操作实现
了解API接口设计(两大顶层接口 Iterator和Map)
Iterator
- 可遍历的数据结构
- 一维结构
- 子类Collection 再往下为 Set 和 List 接口
Map
- 键-值对映射的数据结构
- 二维结构
我们通过查询API可以发现List的结构为 Iterable -----> collection -----> List -----> List的各种实现类。
其中Iterable这个接口主要制定迭代功能,collection这个接口制定集合通用功能,因此collection通常用于传递集合,并在需要最大的通用性的情况下对其进行操作。
在List的众多实现类中,我们常用的一般是ArrayList 和 LinkedList,下面开始介绍
1、ArrayList详解
从上面的文字我们已经知道为什么会出现集合框架,这里我将介绍ArrayList的具体实现。
首先ArrayList的底层其实还是数组,但与数组不同,它是一个提供增删改查方法且动态扩容的对象。
这里的重点在于动态扩容,因为传统数组因为长度固定的原因,每次增删都需要创建一个新的数组进行接收。这些操作都将再ArrayList内部进行不需要我们自己进行操作,而且扩容也是有它自己规律。下面我们来分析ArrayList这部分的源码:
List<Object> list = new ArrayList<>();//通过无参构造器,创建对象
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//这里是将集合中的数组初始化为0个大小
}
list.add("源码");//我们从中添加一个元素,来查看它内部是怎样操作的
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//DEFAULT_CAPACITY为它默认的大小
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果需要的数组长度大于现有长度,则进行扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;//现有数组长度
int newCapacity = oldCapacity + (oldCapacity >> 1);//新的数组长度为现有数组长度的1.5倍
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);//这里是将数组里的值复制到一个大小为 新的数组长度 的数组中,并让集合中的数组指向这个新的数组
}