手动实现arraylist和hashmap
这是第一篇博客,我准备先将最近学习的笔记记录下来,数据结构最基础也最难吧,大佬就别看了。。。 Arraylist public class LouisArraylist<E> { int size; Object[] array; private static final int MIN_CAPACITY_INCREMENT = 12; public LouisArraylist(int capacity){ if(capacity<0){ throw new IllegalArgumentException(); } array = new Object[capacity]; } public LouisArraylist(){ array = new Object[0]; } public LouisArraylist(Collection<? extends E> collection){ Object[] a = collection.toArray(); if(a.getClass()!=Object[].class){ Object[] newArray = new Object[a.length]; System.arraycopy(a, 0, newArray, 0, a.length); a = newArray; } array = a; size = a.length; } /** * 扩容 * */ private static int newCapacity(int currentCapacity){ int increment = (currentCapacity<MIN_CAPACITY_INCREMENT/2)?MIN_CAPACITY_INCREMENT :currentCapacity>>1; return currentCapacity+increment; } /** * 增加 */ public boolean add(E object){ Object[] a = array; int s = size; if(s == a.length){ //需要扩容了 Object[] newArray = new Object[newCapacity(s)]; System.arraycopy(a, 0, newArray, 0, s); array = a = newArray; } a[s] = object; size = s + 1; return true; }