自定义实现ArrayList很简单,只需要明白下面几点
1、ArrayList 底层是由数组组成的
2、数组有容量限制,但是ArrayList并没有(实际上也有,Integer.MAX_VALUE)。在增加数据的时候做好扩容
3、移除数组中的某一个数据要怎么做
下面是我自定义的ArrayList。基本的增删改查是有了。
public class MyArrayList<E> { private int capacity = 10; //arrayList 容量 private Object[] element = new Object[capacity]; //构成arrayList的底层数组 int size; //arrayList中存在的元素 size <= capacity int next; //数组索引 永远指向下一个添加的数据位置 /** * <默认构造函数> */ public MyArrayList() { } /** * <默认构造函数> */ public MyArrayList(int capacity) { this.capacity = capacity; } /** * 添加数据 * <功能详细描述> * @param e * @see [类、类#方法、类#成员] */ public void add(E e) { if(e == null) { throw new NullPointerException("cannot add null object"); } checkSize(); //检查数组容量 if(size <= capacity/2) { //如果size <= capacity/2 不进行扩容直接添加 element[size] = e; size ++; }else { //扩容 growCapacity(); element[size] = e; size ++; } } /** * 获取inde指向的数据 * <功能详细描述> * @param index * @return * @see [类、类#方法、类#成员] */ public E get(int index) { if(index > size-1) { throw new ArrayIndexOutOfBoundsException("index out of size, " + index); } return (E)element[index]; } /** * 移除index指向的数据 * <功能详细描述> * @param index * @see [类、类#方法、类#成员] */ public E remove(int index) { if(index > size-1) { throw new ArrayIndexOutOfBoundsException("index out of size, " + index + "size :" + size); } Object result = element[index]; System.arraycopy(element, index+1, element, index, size-index-1); element[--size] = null; return (E)result; } /** * 修改数据 * <功能详细描述> * @param index * @param e * @see [类、类#方法、类#成员] */ public void change(int index, E e) { if(index > size-1) { throw new ArrayIndexOutOfBoundsException("index out of size, " + index); } if(e == null) { throw new NullPointerException("cannot add null object"); } element[index] = e; } /** * {@inheritDoc} */ public String toString() { StringBuilder sbBuilder = new StringBuilder(); for(int i=0;i<size;i++) { sbBuilder.append("("+i+","+element[i]+"),"); } String result = sbBuilder.toString(); result = result.substring(0,result.length()-1); return result; } /** * 检查容量 * <功能详细描述> * @return * @see [类、类#方法、类#成员] */ private void checkSize() { if(size > capacity || size > Integer.MAX_VALUE) { throw new ArrayIndexOutOfBoundsException("size too large, " + size); } } /** * 将数组进行扩容 * <功能详细描述> * @see [类、类#方法、类#成员] */ private void growCapacity() { if(capacity > Integer.MAX_VALUE) { throw new ArrayIndexOutOfBoundsException("capacity too large, " + capacity); } int newCapacity = capacity + capacity >> 1; //新的容量 = 老容量 + 老容量的1/2 element = Arrays.copyOf(element, newCapacity); capacity = newCapacity; } }
写一个main函数测试一下
public class TestList { public static void main(String[] args) { MyArrayList<String> list = new MyArrayList<String>(); for(int i=0;i<10;i++) { list.add(i+""); } System.out.println(list.toString()); String s = list.get(6); System.out.println(s); System.out.println(list.remove(5)); System.out.println(list.toString()); } }
下面是运行结果