手写ArrayList增删改查(笔记)

  • 闲话少说, 原理大家都懂, 直接上代码


/**
 * 手写一个ArrayList
 * @param <E>
 */
public class MyArrayList<E> {

	/**
	 * 当前存储的容量
	 */
	private int size;

	/**
	 * 存放对象的数组
	 */
	private Object[] objects;
	/**
	 * 数组初始容量
	 */
	private static final int INITIAL_SIZE = 16;

	public MyArrayList() {
		// 初始化数组
		objects = new Object[INITIAL_SIZE];
	}

	/**
	 * 当前存储的元素容量
	 */
	public int size() {
		return size;
	}

	public boolean add(E e) {

		if (size == objects.length) {
			// 扩容
			transferArr();
		}
		objects[size] = e;
		size++;
		return true;
	}

	/**
	 * 指定位置插入元素
	 * @param index
	 * @param e
	 * @return
	 */
	public boolean add(int index, E e) {

		if (index >= size) {
			throw new ArrayIndexOutOfBoundsException();
		}

		if (size == objects.length) {
			transferArr();
		}
		System.arraycopy(objects, index, objects, index + 1, size - index);
		objects[index] = e;
		size++;

		return true;
	}


	/**
	 * 数组扩容
	 */
	private void transferArr() {

		int length = objects.length;
		int half = length >> 1;
		length = length + half;

		Object[] newArr = new Object[length];
		System.arraycopy(objects, 0, newArr, 0, objects.length);
		objects = newArr;

	}


	public E get(int index) {

		if (index < 0 || index >= size) {
			throw new ArrayIndexOutOfBoundsException();
		}

		return (E) objects[index];
	}

	/**
	 * 删除元素
	 */
	public E remove(int index) {
		if (index < 0 || index >= size) {
			throw new ArrayIndexOutOfBoundsException();
		}

		Object object = objects[index];

		if (index == (size - 1)) {
			objects[index] = null;
		} else {
			System.arraycopy(objects, index + 1, objects, index, size - index);

		}
		size--;
		return (E) object;

	}



	/**修改元素, 返回旧的元素*/
	public E set(int index, E e){
		if (index < 0 || index >= size) {
			throw new ArrayIndexOutOfBoundsException();
		}

		Object oldVal = objects[index];
		objects[index] = e;
		return (E) oldVal;
	}

	public int arrLength() {
		return objects.length;
	}


}


  • 参考文献
    jdk源码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值