ArrayList类的学习

ArrayList 类

1、ArrayList概述

1.1 实现的接口

Collection接口 :里面相当于描述List的ADT(抽象数据类型)

常见方法如下:

public interface Collection<E> extends Iterable<E> {
    int size();  // 集合的大小
    boolean isEmpty();  // 是否为空
    void clear();  // 清楚集合的内容
    boolean contains(Object o);  // 是否包含某个元素
    boolean add(E e); // 添加元素
    boolean remove(Object o); // 移除某个元素
    Iterator<E> iterator(); // 返回迭代器对象
    .......  
}

List接口:List接口继承了Collection接口,相当于对以上操作的一个补充

额外添加的方法:

public interface List<E> extends Collection<E> {
    E get(int index); // 根据索引返回元素
    E set(int index, E element); // 修改指定位置元素
    void add(int index, E element);  // 指定位置添加元素,添加位置以后元素全部后移
    E remove(int index); // 删除指定位置的元素,并返回元素
    .......
}

1.2 ArrayList类扩容机制

1)、默认大小

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

可以看出,默认大小为10

2)、数组容量不够时的扩容方法:

① 添加元素时的add方法

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

ensureCapacityInternal方法会检测数组的容量,若容量不够按照相应的规则进行扩展。

② 流程方法

private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

// 计算容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        // 若数组是空数组,则返回默认的 DEFAULT_CAPACITY 和传入的 minCapacity较大的数
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    // 否则直接返回 minCapacity
    return minCapacity;
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;  // 计算数组操作的次数

    // overflow-conscious code
    if (minCapacity - elementData.length > 0) // 若这里为true,说明本来的数组容量不够用,需要扩容
        grow(minCapacity);
}

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length; // 记录原本数组的长度
    int newCapacity = oldCapacity + (oldCapacity >> 1); // 相当于oldCapacity x 1.5,即原本数组的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);
}

2、简易ArrayList类的实现

package cn.codingboy.datastructure.List;

import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * 学习 java.util.ArrayList 的实现
 */
public class MyArrayList<T> {

    private static final int DEFAULT_CAPACITY = 10; // 定义默认容量

    private int size;  // 定义大小

    private T[] Items; // 定义存储数组

    public MyArrayList() {
        doClear();
    }

    public void clear() {
        doClear();
    }

    private void doClear() {
        size = 0;
        ensureCapacity(DEFAULT_CAPACITY);
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public void trimToSize() {
        ensureCapacity(size());
    }

    public T get(int index) {
        if (index < 0 || index >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        return Items[index];
    }

    public T set(int index, T newVal) {
        if (index < 0 || index >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        T old = Items[index];
        Items[index] = newVal;
        return old;
    }

    private void ensureCapacity(int newCapacity) {
        if (newCapacity < size) {
            return;
        }
        T[] old = Items;
        // 直接创建泛型类是非法的,这里创建Object类,然后进行强转
        Items = (T[]) new Object[newCapacity];
        for (int i = 0; i < size(); i++) {
            Items[i] = old[i];
        }
    }

    public boolean add(T x) {
        add(size(), x);
        return true;
    }

    private void add(int index, T x) {
        if (Items.length == size()) {
            ensureCapacity(size() * 2 + 1);
        }
        for (int i = size; i > index; i--) {
            Items[i] = Items[i - 1];
        }
        Items[index] = x;
        size++;
    }

    public T remove(int index) {
        T rem = Items[index];
        for (int i = index; i < size() - 1; i++) {
            Items[i] = Items[i + 1];
        }
        size--;
        return rem;
    }

    public Iterator<T> iterator() {
        return new ArrayListIterator();
    }

    private class ArrayListIterator implements Iterator<T> {

        private int current = 0;

        @Override
        public boolean hasNext() {
            return current < size();
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return Items[current++];
        }

        @Override
        public void remove() {
            MyArrayList.this.remove(--current);
        }
    }

    public static void main(String[] args) {
        MyArrayList list = new MyArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值