本文主要是介绍容器第三课,JDK源码分析,自己实现ArrayList数组扩容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.pkushutong.Collection;/*** 测试底层方法的实现,参照这JDK源码* @author dell**/
public class Test02{private Object[] elementData;private int size;private int size(){return size;}private boolean isEmpty(){return size == 0;}public Object get(int index){rangeCheck(index);return elementData[index];}public Test02(){this(10);}public Test02(int initialCapacity){if(initialCapacity < 0 ){try {throw new Exception();} catch (Exception e) {e.printStackTrace();}}elementData = new Object[initialCapacity];}public void add(Object obj){//数组扩容if(size == elementData.length){Object[] NewObject = new Object[size * 2 + 1];//旧数组数据拷贝到新数组里System.arraycopy(elementData, 0, NewObject, 0, elementData.length);elementData = NewObject;}elementData[size++] = obj;}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 obj){for(int i=0; i<size; i++){if(get(i).equals(obj)){remove(i);}}}public Object set(int index, Object obj){rangeCheck(index);Object oldValue = elementData[index];elementData[index] = obj;return oldValue;}private void rangeCheck(int index){if(index < 0 || index >= size){try {throw new Exception();} catch (Exception e) {e.printStackTrace();}}}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[] NewObject = new Object[size * 2 + 1];//旧数组数据拷贝到新数组里System.arraycopy(elementData, 0, NewObject, 0, elementData.length);elementData = NewObject;}}public static void main(String[] args) {Test02 t = new Test02(3);t.add("123");t.add("234");t.add("345");t.add("456");t.add("567");System.out.println(t.size());System.out.println(t.get(5));}
}
这篇关于容器第三课,JDK源码分析,自己实现ArrayList数组扩容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!