手写ArrayList


模仿jdk中的源码写一写关于collection接口,其中ArrayList是List的实现类,在ArrayList中底层实现依然是数组,只不过在会随着数据量的增加会自动扩容, 自动扩容的机制便是new一个更大的数组,然后将引用指过去便可以了,在模仿jdk源码过程中会发现里面会有很多容错性检查,而且类之间的调用也很有规范,给外面的接口一律将权限设为public,而内部调用函数便设为private.实现更好的封装,代码重用性也提高很多。

另外发现jdk中将elementData数组定义为transient,关于transient的用法参照transient


package com.huat.ArrayList;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author yanzz
 * @编辑时间:2018年3月17日
 * @功能说明:手写ArrayList
 * @version:
 */
public class MyArrayList {

	private int size;

	private Object[] elementData;

	public MyArrayList() {
		this(10);
	}

	public MyArrayList(int initalCapacity) {

		if (initalCapacity < 0) {
			try {
				throw new Exception("erro");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		this.elementData = new Object[initalCapacity];
	}

	public int size() {
		return size;
	}

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

	public void add(Object o) {
		// 数组扩容,先拷贝的一个数组在将引用冲洗指向新的数组中
		if (size == elementData.length) {
			Object[] newArray = new Object[size * 2 + 1];
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			this.elementData = newArray;
		}

		elementData[size++] = o;
	}

	private void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			try {
				throw new Exception("erro");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public Object get(int index) {

		rangeCheck(index); // jdk中把检查数组下标做成一个方法,保持重用性

		return elementData[index];
	}

	public void remove(int index) {

		rangeCheck(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

	}

	public void remove(Object o) {

		for (int i = 0; i < size; i++) {
			if (get(i).equals(o)) {
				remove(i);
			}
		}
	}

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

		Object oldValue = elementData[index];
		elementData[index] = element;
		return oldValue;
	}

	public void add(int index, Object obj) {
		rangeCheck(index);
		
		ensureCapacityInternal();
		
		System.arraycopy(elementData, index, elementData, index + 1,
				size - index);
		elementData[index] = obj;
		size++;
	}

	private void ensureCapacityInternal() {
		if (size == elementData.length) {
			Object[] newArray = new Object[size * 2 + 1];
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			this.elementData = newArray;
		}
	}
	
	public static void main(String[] args) {
		MyArrayList list = new MyArrayList(3);
		list.add("daf");
		list.add("bbb");
		list.add("bbb");
		list.add("aad");
		list.add("bbb");
		list.add("bbb");
		list.add("bbb");
		list.add("bbb");
		System.out.println(list.size());
		System.out.println(list.get(3));
		list.add(2,"cccc");
		System.out.println(list.get(2));
	}
}

你可能感兴趣的:(java)