标签:
最近在实习期被公司送到归谷培训,在老师布置做的时候,理论上用ArrayList很方便,只可以他还没讲,我自己用的话有种作弊的感觉,后来突发奇想相自己用数组写一个仿ArrayList.
/** * @ClassName: MyList * @Description: 仿ArrayList * @author Lmc * @date 2015-11-5 下午06:34:59 */ public class MyList<T>{ /** * @Fields defaultSize : 初始化数组长度 * 默认长度应该为10,为了方便测试 定为2 */ private int defaultSize = 2; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //T[] entity; /** * @Fields nowSize : 当前数组长度 */ int size=0; Object[] elementData; public MyList(){ elementData = new Object[defaultSize]; } public MyList(int listSize){ if (listSize < 0) throw new IllegalArgumentException("Illegal Capacity: "+ listSize); elementData = new Object[listSize]; } /** * @Title: add 添加一个元素 * @Description: */ public void add(T element){ //判断数组内元素个数是否超过上限,超过则扩充数组 ensureCapacityInternal(size+1);//size+1为所需的最小容量 elementData[size++] = element; } /** * @Title: get * @Description: 获取第index个元素 */ public T get(int index){ rangeCheck(index); return (T)elementData[index]; } /** * @Title: remove * @Description: 移除list中的第index个元素 * @return T 第index个元素 */ public T remove(int index) { rangeCheck(index); T oldValue = (T)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; } /** * @Title: size * @Description: 获得当前数据的个数(也可以说是list的长度) */ public int size(){ return size; } /** * @Title: rangeCheck * @Description: 判断index是否超过数组范围 */ private void rangeCheck(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * @Title: outOfBoundsMsg * @Description: 数组越界提示信息 */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+this.size; } /** * @Title: ensureCapacityInternal * @Description: 判断当前是否需要扩增数组大小 * @param size 当前数组里实际的元素个数 */ private void ensureCapacityInternal(int minCapacity) { if(minCapacity - elementData.length > 0){ grow(minCapacity); } } /** * @Title: grow * @Description: 增加数组的范围 数组大小变为原来的1.5倍 * (jdk1.7)新特性如果扩容后仍小于最小需求容量,则直接扩容到最小需求容量 位运算速度快 * (jdk1.6以前)则是扩容到1.5倍+1; */ private void grow(int minCapacity){ int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); //Object[] newElementData = new Object[newCapacity]; //System.arraycopy(elementData, 0, newElementData, 0, nowSize); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); // System.out.println("开始扩增数组大小"); } /** * @Title: hugeCapacity * @Description: 处理扩容时 容量已经超过定义的最大容量 */ private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } }
标签:
原文地址:http://my.oschina.net/u/2374259/blog/526648