手撕ArrayList底层,透彻分析源码(1)

private void grow(int minCapacity) {

int oldCapacity = elementData.length;

int newCapacity = oldCapacity + (oldCapacity >> 1);

if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;

if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);

elementData = Arrays.copyOf(elementData, newCapacity);
}

(1) 这里先拿到原来数据elementData的长度赋给一个变量oldCapacity,然后将原来的长度扩大1.5倍并付给oldCapacity。

(2) 判断minCapacity 是否大于newCapacity,成立则将minCapacity赋给newCapacity,为什么要这么做呢?因为从前的一层层的方法进行解析之后来看,minCapacity是允许扩容后的最小长度,也就是实际存有数据的最小长度,要是你扩容后的长度还比minCapacity要小,那么只能将minCapacity作为容器的长度。

(3) 然后判断容器新长度newCapacity是否大于容器所允许的最大长度MAX_ARRAY_SIZE,成立则将扩容长度设置为最大可用长度。

(4) 拷贝,扩容,构建一个新的数组。

接着我们来看看grow方法调用的hugeCapacity的源码:

private static int hugeCapacity(int minCapacity) {

if (minCapacity < 0) // overflow
throw new OutOfMemoryError();

return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}

(1) 直接判断minCapacity是否小于零,成立抛出异常,然后比较容器所允许的最小长度值是否大于MAX_ARRAY_SIZE,成立则将Integer的最大值赋值给minCapacity作为容器的最大长度。

add(int index, E element)方法

public void add(int index, E element) {

rangeCheckForAdd(index);

ensureCapacityInternal(size + 1); // Increments modCount!!

System.arraycopy(elementData, index, elementData, index + 1,size - index);

elementData[index] = element;
size++;
}

(1)  这里主要做三件事,第一件就是判断下标是否越界,如果是则抛出IndexOutOfBoundsException异常。

(2) 然后就是判断是否需要扩容,这个方法和上面的一样,已经说过了,就不再赘述了。

(3) 最后就是执行数组对象index后的对象后移一位,将元素添加到指定位置。

接下来我们来看看rangeCheckForAdd的源码

private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

(1) 直接就是判断index > size或者index < 0条件,成立就直接抛出数组下标越界异常。

addAll(Collection c)方法

public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {

rangeCheckForAdd(index);

int cSize = c.size();

if (cSize==0)
return false;

checkForComodification();

parent.addAll(parentOffset + index, c);

this.modCount = parent.modCount;

this.size += cSize;
return true;
}

private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}

(1) addAll(Collection c)方法里面直接调用addAll(this.size, c),在addAll(this.size, c)里面第一件事就是判断是否下标越界。

(2) 然后判断c的大小是否大于0,如果等于0 返回 false。

(3) 检查修改的次数是否相等,若不相等直接则抛出ConcurrentModificationException(并发修改)异常,这个也就是当我们用迭代器循环list的时候,在其中用list的方法新增/删除元素,就会出现这个错误。

(4) 将元素插入到数组中,将修改次数赋值给 modCount,最后size大小加一

(5) 在进行 add 操作时先判断下标是否越界,是否需要扩容,如果需要扩容,就复制数组,默认扩容一半,如果扩容一半不够的话,就用目标的size作为扩容后的容量,然后设置对应的下标元素值。

get()方法

public E get(int index) {
rangeCheck(index);
return elementData(index);
}

private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

E elementData(int index) {
return (E) elementData[index];
}

(1) 这个就很简单了直接就是先判断是否下标越界,越界就抛出异常,最后返回指定index位置的元素值。

set()方法

public E set(int index, E element) {
rangeCheck(index);

E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

(1) 先判断是否越界,然后取出原来index位置的值为oldValue,将新的值element设置到index位置,最后将旧的值oldValue返回。

remove()方法

public E remove(int 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;
}

(1) 判断是否越界,然后将修改次数modCount值加1,然后就是获得原来index位置的旧值。

(2) 然后是计算index位置后面有多少个元素,接着将index位置后的元素向前移动一位,最后将旧值返回。

remove(Object o)方法

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
}

(1) 这个根据对象删除的方法比较简单,首先判断o对象是否为null对象,为null就遍历集合中的元素,是否存在null值,存在执行删除,删除指定对象的方法是fastRemove,原理就是计算index位置后的元素个数,然后将index后的元素都往前移动一位,最后将最后的一位赋值为null值。

(2) 若o对象是不为null对象的时候,执行的逻辑是一样的,那么为什么要分开写呢?很简单,因为它后面要调用o.equals(elementData[index]方法进行判断,要是为null,不就报空指针异常了。

Iterator迭代器

public Iterator iterator() {
return new Itr();
}

private class Itr implements Iterator {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
Itr() {}

public boolean hasNext() {
return cursor != size;
}

@SuppressWarnings(“unchecked”)
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();

Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();

cursor = i + 1;
return (E) elementData[lastRet = i];
}

public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();

try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}

(1) 迭代器中有几个属性比较重要,int cursor是下一个要返回的元素的索引, int lastRet = -1  是返回的最后一个元素的索引,默认为-1,就是没有的情况。

最后

看完美团、字节、腾讯这三家的面试问题,是不是感觉问的特别多,可能咱们又得开启面试造火箭、工作拧螺丝的模式去准备下一次的面试了。

开篇有提及我可是足足背下了1000道题目,多少还是有点用的呢,我看了下,上面这些问题大部分都能从我背的题里找到的,所以今天给大家分享一下互联网工程师必备的面试1000题

注意不论是我说的互联网面试1000题,还是后面提及的算法与数据结构、设计模式以及更多的Java学习笔记等,皆可分享给各位朋友

最新“美团+字节+腾讯”一二三面问题,挑战一下你能走到哪一面?

互联网工程师必备的面试1000题

而且从上面三家来看,算法与数据结构是必备不可少的呀,因此我建议大家可以去刷刷这本左程云大佬著作的《程序员代码面试指南 IT名企算法与数据结构题目最优解》,里面近200道真实出现过的经典代码面试题

最新“美团+字节+腾讯”一二三面问题,挑战一下你能走到哪一面?

的互联网面试1000题,还是后面提及的算法与数据结构、设计模式以及更多的Java学习笔记等,皆可分享给各位朋友

[外链图片转存中…(img-M0eSjt8j-1714712073542)]

互联网工程师必备的面试1000题

而且从上面三家来看,算法与数据结构是必备不可少的呀,因此我建议大家可以去刷刷这本左程云大佬著作的《程序员代码面试指南 IT名企算法与数据结构题目最优解》,里面近200道真实出现过的经典代码面试题

[外链图片转存中…(img-HI1LyD1A-1714712073542)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值