自定义实现ArrayList
"双十一让你明白,有些东西,打半折你也买不起;就像你喜欢的人,眼光降低一半,还是看不上你“。所以,在JDK1.8中,ArrayList底层是怎么实现的呢?(看源码能理解就行)
/** * 自定义实现ArrayList */ public class TextArrayList<E> { private Object[] elementData; private int size; private static final int DEFALT_CAPACITY = 10; /** * 无参构造,默认数组大小为10 */ public TextArrayList() { elementData = new Object[DEFALT_CAPACITY]; } /** * 有参构造,数组大小为传入的值 */ public TextArrayList(int capacity) { if (capacity < 0) { throw new RuntimeException("容器容量不能为负数"); } else if (capacity == 0) { elementData = new Object[DEFALT_CAPACITY]; } else { elementData = new Object[capacity]; } } /** * 给数组中添加元素 * * @param element */ public void add(E element) { //数组扩容 if (size == elementData.length) { Object[] newArray = new Object[elementData.length + (elementData.length >> 1)]; System.arraycopy(elementData, 0, newArray, 0, elementData.length); elementData = newArray; } elementData[size++] = element; } /** * 删除元素 * 挨个比较所有元素,获得第一个比较结果为True的,返回 * * @return */ public void remove(E element) { for (int i = 0; i < size; i++) { if (element.equals(get(i))) { //比较操作用到equals方法 System.arraycopy(elementData, i + 1, elementData, i, elementData.length - i - 1); elementData[size - 1] = null; size--; } } } /** * 删除索引 * * @return */ public void remove(int index) { int numMoved = elementData.length - index - 1; if (numMoved > 0) { System.arraycopy(elementData, index + 1, elementData, index, numMoved); } elementData[size - 1] = null; size--; } /** * 判空 * * @return */ public boolean isEmpty() { return size == 0 ? true : false; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); //[a,b,c] stringBuilder.append("["); for (int i = 0; i < size; i++) { stringBuilder.append(elementData[i] + ","); } stringBuilder.setCharAt(stringBuilder.length() - 1, ']'); return stringBuilder.toString(); } /** * 增加get方法 * * @param index */ public E get(int index) { checkRange(index); return (E) elementData[index]; } /** * 增加set方法 * * @param index */ public void set(E element, int index) { checkRange(index); elementData[index] = element; } //判断索引合法性 public void checkRange(int index) { if (index < 0 || index > size - 1) { throw new RuntimeException("索引不合法:" + index); } } public static void main(String[] args) { TextArrayList t1 = new TextArrayList(20); // t1.add("aa"); // t1.add("bb"); for (int i = 0; i < 40; i++) { t1.add("wang" + i); } t1.set("sss", 10); System.out.println(t1); System.out.println(t1.get(39)); t1.remove(3); t1.remove("wang5"); System.out.println(t1); System.out.println(t1.size); System.out.println(t1.isEmpty()); } }