//判断一个元素是否在列表中,如果存在,返回第一个靠前位置的下标,如果不存在,返回-1。 public int indexOf(Object o) { // 如果传入的对象为null,则看有没有对象为null在列表中 if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; // 调用Object的equals方法来进行比较两个元素是否相等 } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
lastIndexOf(Object o) 方法
1 2 3 4 5 6 7 8 9 10 11 12 13
//找到一个元素在列表中最后一个出现的索引并返回,没找到返回-1,和indexOf方法,只是遍历数组时倒叙遍历而已,不赘述。 public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; }
clone()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// clone方法是Object类的方法,返回当前ArrayList的一个副本 public Object clone() { try { // v为赋值的实例属性 ArrayList<?> v = (ArrayList<?>) super.clone(); //数据和modCount赋值 v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } }
toArray()方法
1 2 3 4
//返回一个Object数组,直接调用Arrays中的copyof方法 public Object[] toArray() { return Arrays.copyOf(elementData, size); }
toArray(T[] a)方法
1 2 3 4 5 6 7 8 9 10 11 12
// 将ArrayList中的元素赋值到一个数组中去 @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // 如果a的长度小于ArrayList的长度,返回一个包含ArrayList所有元素的数组 return (T[]) Arrays.copyOf(elementData, size, a.getClass()); // 将ArrayList额elementData数组复制到a数组,然后将a数组的size位置赋值为空。 System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
get(int index)方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 获取指定下标的元素并返回,可以看出get方法其实就是两个方法的封装 public E get(int index) { rangeCheck(index);
return elementData(index); }
// 检查index是否超出了ArrayList的size。 private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
// 移除指定index位置的元素并返回该元素 public E remove(int index) { // 检查index是否小于elementData长度 rangeCheck(index);
modCount++; // 旧值 E oldValue = elementData(index);
int numMoved = size - index - 1; if (numMoved > 0) // 将index位置的元素顺次向前移动一位 System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work // 返回旧值 return oldValue; }
// 从ArrayList中删除从0开始第一个遇到的o元素,成功返回true,失败返回false public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) // 找到o的下标 if (o.equals(elementData[index])) { // 移除元素index fastRemove(index); return true; } } return false; }
// 快速移除index下标处的元素 private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) // 将index位置的元素顺次向前移动一位 System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
clear()方法
1 2 3 4 5 6 7 8 9 10
// 从ArrayList中移除所有元素 public void clear() { modCount++;
// 将elementData中所有元素设置为空 for (int i = 0; i < size; i++) elementData[i] = null;
// 序列化方法,将列表状态写入数据流中 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone() s.writeInt(size);
// Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); }
if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
// 获取列表指定位置的迭代器对象 public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); }
// 获取list开头的迭代器对象 public ListIterator<E> listIterator() { return new ListItr(0); }
// Itr 内部类 private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount;
public boolean hasNext() { return cursor != size; }
@SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification();
@Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); }
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
// 是否有上一个迭代对象 public boolean hasPrevious() { return cursor != 0; } // 获取当前迭代对象的下标 public int nextIndex() { return cursor; } // 获取上一个迭代对象的下标 public int previousIndex() { return cursor - 1; }
@SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; }
public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification();
// 从列表中取出指定位置的子列表 public List<E> subList(int fromIndex, int toIndex) { // 起点和终点的下标检查 subListRangeCheck(fromIndex, toIndex, size); // 调用SubList内部类来实现字列表的实现 return new SubList(this, 0, fromIndex, toIndex); }
// 起点和终点的下标检查 static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); }
// SubList内部类,对ArrayList数组直接进行增删改查,只是为其限定了边界 private class SubList extends AbstractList<E> implements RandomAccess { private final AbstractList<E> parent; private final int parentOffset; private final int offset; int size; // 构造方法,父列表,偏移量,fromIndex,toIndex SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; }
public E set(int index, E e) { rangeCheck(index); checkForComodification(); E oldValue = ArrayList.this.elementData(offset + index); ArrayList.this.elementData[offset + index] = e; return oldValue; }
public E get(int index) { rangeCheck(index); checkForComodification(); return ArrayList.this.elementData(offset + index); }
public int size() { checkForComodification(); return this.size; }
public void add(int index, E e) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount; this.size++; }
public E remove(int index) { rangeCheck(index); checkForComodification(); E result = parent.remove(parentOffset + index); this.modCount = parent.modCount; this.size--; return result; }
// Collection方法中的增强型for循环 @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
Sort方法
1 2 3 4 5 6 7 8 9 10 11
// 传入比较器,对ArrayList进行排序 @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++; }
近期评论