1、实现RandomAccess接口,建议采用fori循环,效率要比迭代Iterator要高。
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
2、ArrayList的底层为数组
private static final int DEFAULT_CAPACITY = 10; //默认的数组大小 private static final Object[] EMPTY_ELEMENTDATA = {}; //空的数组 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //默认长度的数组 transient Object[] elementData; // 被transient的属性不会被序列化,字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化
3、size表示list包含元素的个数
/** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
4、有参构造函数,指定list长度,如果initialCapacity>0,那么生成指定长度的数组,initialCapacity==0,生成默认的空数组,initialCapacity<0,抛出IllegalArgumentException异常
public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }
5、无参构造函数,默认数组长度为十
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
6、如果c元素不为空,生成内容为c的list
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) //原因参考:https://www.cnblogs.com/cmdra/p/5901793.html elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
7、举例:当一个默认长度为10的ArrayList,又增加一个元素时,动态增长内存长度为15,该方法就是通过Arrays.copyOf(elementData, size)生成指定长度的list去除多余内存长度
/** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } }
8、get(index) 首先校验是否数组越界,然后返回elementData[index]
public E get(int index) { rangeCheck(index); return elementData(index); }
9、set(int,E)
public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
10、add(E e)方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!! 提前校验增长后长度,有必要的话先预增长
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果elementData是默认长度10的空list minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); // minCapacity 取两者中的较大值 } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) //判断增加元素后的长度是否大于现在的arraylist的创建大小,大于的话就增长 grow(minCapacity); }
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //新创建的数组长度为原来的1.5倍
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
11、E remove(int index) 还有一个fastmove的方法,不同点在于去除了rangeCheck(index)的判断
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = 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; }
12、 截取,左闭右开
public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); }
13、removeIf(Predicate<? super E> filter) 自定义一个CommonPredicate类实现Predicate<T>接口,定义一个属性varc1,实现test接口,重新test逻辑,然后使用的时候定义CommonPredicate.varc1值为你想要筛选的条件,就可以达到筛选的效果
@Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); // figure out which elements are to be removed // any exception thrown from the filter predicate at this stage // will leave the collection unmodified int removeCount = 0; final BitSet removeSet = new BitSet(size); final int expectedModCount = modCount; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { @SuppressWarnings("unchecked") final E element = (E) elementData[i]; if (filter.test(element)) { removeSet.set(i); removeCount++; } } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } // shift surviving elements left over the spaces left by removed elements final boolean anyToRemove = removeCount > 0; if (anyToRemove) { final int newSize = size - removeCount; for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) { i = removeSet.nextClearBit(i); elementData[j] = elementData[i]; } for (int k=newSize; k < size; k++) { elementData[k] = null; // Let gc do its work } this.size = newSize; if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } return anyToRemove; }
14、replaceAll(UnaryOperator<E> operator) 同上,可以根据自己的要求重写替换逻辑
@Override @SuppressWarnings("unchecked") public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { elementData[i] = operator.apply((E) elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
//列子 public class CommonPredicate<T> implements Predicate<T> { T filter; @Override public boolean test(T t) { if (filter.equals( t )) { return true; } else { return false; } } }
public class ArrayListTest { private static CommonPredicate<Object> predicate = new CommonPredicate<>(); private static CommonUnaryOperator<Object> unaryOperator = new CommonUnaryOperator<>(); public static void main(String[] args) { predicate.filter = (2); unaryOperator.varc1=(2); ArrayList<Object> list1 = new ArrayList<>(); list1.add( 1 ); list1.add( 2 ); list1.add( 3 ); list1.add( 2 ); //list1.removeIf( predicate ); //打印出来的结果是1 3 list1.replaceAll( unaryOperator ); //打印出来的结果是2 99 2 99 list1.forEach( o -> System.out.println( o ) ); } }
15、sort(Comparator<? super E> c),见下面例子
@Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
---------------------例子----------------------
@Data
public class Student {
String name;
Integer id;
public Student(Integer id,String name) {
this.name = name;
this.id = id;
}
}
public class StudentComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { return o1.id.compareTo( o2.id ); } }
public class SortTest { public static void main(String[] args) { StudentComparator studentComparator = new StudentComparator(); List<Student> myList = new ArrayList<>(); myList.add( new Student( 4, "David" ) ); myList.add( new Student( 2, "Tom" ) ); myList.add( new Student( 5, "Rohit" ) ); myList.add( new Student( 1, "Paul" ) ); myList.add( new Student( 3, "Vishal" ) ); myList.sort( studentComparator ); System.out.println( myList ); } } 打印结果:[Student(name=Paul, id=1), Student(name=Tom, id=2), Student(name=Vishal, id=3), Student(name=David, id=4), Student(name=Rohit, id=5)]