• JDK1.8源码ArrayList


    线程不安全的,如果要想线程安全必须在创建的时候就采用线程安全的方式创建:

    1 List list = Collections.synchronizedList(new ArrayList(...));

    引用博文链接 : http://www.cnblogs.com/leskang/p/6019887.html

    构造器:

     1 public class ArrayList<E> extends AbstractList<E>
     2         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
     3 {
     4     private static final long serialVersionUID = 8683452581122892189L;
     5 
     6     //默认初始大小:10
     7     private static final int DEFAULT_CAPACITY = 10;
    //记录列表结构性修改次数,next,add,remove,previous,set操作
    8 protected transient int modCount = 0; 9 //空数组 10 private static final Object[] EMPTY_ELEMENTDATA = {}; 11 12 //默认大小空数组 13 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; 14 15 transient Object[] elementData; // non-private to simplify nested class access 16 17 private int size; 18 19 //构建一个大小指定的空列表 20 public ArrayList(int initialCapacity) { 21 if (initialCapacity > 0) { 22 this.elementData = new Object[initialCapacity]; 23 } else if (initialCapacity == 0) { 24 this.elementData = EMPTY_ELEMENTDATA; 25 } else { 26 throw new IllegalArgumentException("Illegal Capacity: "+ 27 initialCapacity); 28 } 29 } 30 31 //构建一个默认大小(10)的空列表 32 public ArrayList() { 33 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; 34 } 35 44 //构建一个包含集合元素的列表,元素排列顺序是按集合的迭代器返回的顺序 45 public ArrayList(Collection<? extends E> c) { 46 elementData = c.toArray(); 47 if ((size = elementData.length) != 0) { 48 // c.toArray might (incorrectly) not return Object[] (see 6260652) 49 if (elementData.getClass() != Object[].class) 50 elementData = Arrays.copyOf(elementData, size, Object[].class); 51 } else { 52 // replace with empty array. 53 this.elementData = EMPTY_ELEMENTDATA; 54 } 55 } 56 ...... 57 }

    boolean add(E e):

     1     public boolean add(E e) {
     2         ensureCapacityInternal(size + 1);  // Increments modCount!! // 添加之前检查数组容量,size+1表示接下来要有的容量
     3         elementData[size++] = e;  
     4         return true;
     5     }
     6     
     7     private void ensureCapacityInternal(int minCapacity) {
     8         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//如果elementData 为空集合
     9             minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//将传入的minCapacity和默认值10比较,选出较大的
    10         }
    11 
    12         ensureExplicitCapacity(minCapacity);
    13     }
    14     
    15     private void ensureExplicitCapacity(int minCapacity) {
    16         modCount++;
    17 
    18         // overflow-conscious code
    19         if (minCapacity - elementData.length > 0)//如果最小容量大于列表现有的长度,则扩容,否则容量不变
    20             grow(minCapacity);
    21     }
    22     
    23     private void grow(int minCapacity) {
    24         // overflow-conscious code
    25         int oldCapacity = elementData.length;
    26         int newCapacity = oldCapacity + (oldCapacity >> 1);//>> : 右移运算符,num >> 1,相当于num除以2,此处扩容按照原容量大小的一半扩容
    27         if (newCapacity - minCapacity < 0)
    28             newCapacity = minCapacity;
    29         if (newCapacity - MAX_ARRAY_SIZE > 0)//如果新容量大于integer的最大值
    30             newCapacity = hugeCapacity(minCapacity);
    31         // minCapacity is usually close to size, so this is a win:
    32         elementData = Arrays.copyOf(elementData, newCapacity); //将原有元素拷贝到扩容后的新数组中
    33     }
    34     
    35      private static int hugeCapacity(int minCapacity) {
    36         if (minCapacity < 0) // overflow
    37             throw new OutOfMemoryError();
    38         return (minCapacity > MAX_ARRAY_SIZE) ?   //如果新容量大于(integer的最大值-8),最大容量就是integer的最大值
    39             Integer.MAX_VALUE :
    40             MAX_ARRAY_SIZE;
    41     }

    总结:ArrayList列表的最大容量就integer的最大值

     

     E remove(int index):

     1   public E remove(int index) {
     2         rangeCheck(index);
     3 
     4         modCount++;
     5         E oldValue = elementData(index);//要移除位置上的元素
     6 
     7         int numMoved = size - index - 1;
     8         if (numMoved > 0)
     9             System.arraycopy(elementData, index+1, elementData, index,
    10                              numMoved);  
    11         elementData[--size] = null; // clear to let GC do its work 将最后一个元素置null回收
    12 
    13         return oldValue;
    14     }
    15 
    16     //System类的方法,从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
    17     从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。被复制的组件的编号等于 length 参数。
    18     源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。
    19     即目标数组的后半段被原数组的后半段(去掉要移除部分)
    20     public static native void arraycopy(Object src,  int  srcPos,
    21                                         Object dest, int destPos,
    22                                         int length);

    add(int index, E element):

    1  public void add(int index, E element) {
    2         rangeCheckForAdd(index);
    3 
    4         ensureCapacityInternal(size + 1);  // Increments modCount!!
    5         System.arraycopy(elementData, index, elementData, index + 1,
    6                          size - index);
    7         elementData[index] = element;//index的位置置为element
    8         size++;
    9     }

    总结:ArrayList增删比较慢

    addAll:
    1      public boolean addAll(Collection<? extends E> c) {
    2          Object[] a = c.toArray();
    3          int numNew = a.length;
    4          ensureCapacityInternal(size + numNew);  // Increments modCount
    5          System.arraycopy(a, 0, elementData, size, numNew);
    6          size += numNew;
    7          return numNew != 0;
    8      }
     1     public boolean addAll(int index, Collection<? extends E> c) {
     2         rangeCheckForAdd(index);
     3 
     4         Object[] a = c.toArray();
     5         int numNew = a.length;
     6         ensureCapacityInternal(size + numNew);  // Increments modCount
     7 
     8         int numMoved = size - index;
     9         if (numMoved > 0) //如果是列表中间位置插入,先将列表index到index+numNew之间的位置空出来
    10             System.arraycopy(elementData, index, elementData, index + numNew,
    11                              numMoved);
    12 
    13         System.arraycopy(a, 0, elementData, index, numNew);//将新添加的元素添加到空出的位置,这里省了一个numMoved==0的判断
    14         size += numNew;
    15         return numNew != 0;
    16     }
    17 
    18     //检查脚标是否越界
    19     private void rangeCheckForAdd(int index) {
    20         if (index > size || index < 0)
    21             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    22     }
    boolean remove(Object o):
     1  public boolean remove(Object o) {
     2         if (o == null) {
     3             for (int index = 0; index < size; index++)
     4                 if (elementData[index] == null) {
     5                     fastRemove(index);
     6                     return true;
     7                 }
     8         } else {
     9             for (int index = 0; index < size; index++)
    10                 if (o.equals(elementData[index])) {
    11                     fastRemove(index);
    12                     return true;
    13                 }
    14         }
    15         return false;
    16     }
    17 
    18     //此方法和remove类似,没有检查索引是否越界
    19     private void fastRemove(int index) {
    20         modCount++;
    21         int numMoved = size - index - 1;
    22         if (numMoved > 0)
    23             System.arraycopy(elementData, index+1, elementData, index,
    24                              numMoved);
    25         elementData[--size] = null; // clear to let GC do its work
    26     }

    总结:先判断是否是null,如果是要单独操作;否则通过逐个比较元素来判断要移除元素的位置,再通过类似于remove的方法移除元素

    E set(int index, E element):修改
    1     public E set(int index, E element) {
    2         rangeCheck(index);
    3 
    4         E oldValue = elementData(index);
    5         elementData[index] = element;
    6         return oldValue;
    7     }

    总结:直接替换指定位置的元素

    E get(int index):
     1     public E get(int index) {
     2         rangeCheck(index);
     3 
     4         return elementData(index);
     5     }
     6 
     7     @SuppressWarnings("unchecked")
     8     E elementData(int index) {
     9         return (E) elementData[index];
    10     }

    总结:根据数组脚标拿到元素,所以速度快

    其他一些方法 :

      1     //修剪列表的容量到最小值,
      2     public void trimToSize() {
      3         modCount++;
      4         if (size < elementData.length) {
      5             elementData = (size == 0) //如果size==0,容量是默认值10,
      6               ? EMPTY_ELEMENTDATA
      7               : Arrays.copyOf(elementData, size);//否则将数组拷贝到一个新的数组(长度为size)
      8         }
      9     }
     10     
     11     //确保列表容量增加到minCapacity
     12     public void ensureCapacity(int minCapacity) {
     13         //如果列表为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,即空列表,则列表容量为默认值10,
     14         否则为0
     15         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
     16             // any size if not default element table
     17             ? 0
     18             // larger than default for default empty table. It's already
     19             // supposed to be at default size.
     20             : DEFAULT_CAPACITY;
     21 
     22         if (minCapacity > minExpand) {
     23             ensureExplicitCapacity(minCapacity);
     24         }
     25     }
     26 
     27     //判断列表元素个数是否为0
     28     public boolean isEmpty() {
     29         return size == 0;
     30     }
     31 
     32     public boolean contains(Object o) {
     33         return indexOf(o) >= 0;
     34     }
     35 
     36     //判断元素o在列表里存在的位置,如果存在返回index,如果不存在返回-1
     37     public int indexOf(Object o) {
     38         if (o == null) {
     39             for (int i = 0; i < size; i++)
     40                 if (elementData[i]==null)
     41                     return i;
     42         } else {
     43             for (int i = 0; i < size; i++)
     44                 if (o.equals(elementData[i]))
     45                     return i;
     46         }
     47         return -1;
     48     }
     49 
     50     //判断元素o最后一次出现的位置,如果存在返回index,如果不存在返回-1
     51     public int lastIndexOf(Object o) {
     52         if (o == null) {
     53             for (int i = size-1; i >= 0; i--)//从列表尾部开始遍历,第一次出现
     54                 if (elementData[i]==null)
     55                     return i;
     56         } else {
     57             for (int i = size-1; i >= 0; i--)
     58                 if (o.equals(elementData[i]))
     59                     return i;
     60         }
     61         return -1;
     62     }
     63 
     64     //克隆浅表副本 
     65     public Object clone() {
     66         try {
     67             ArrayList<?> v = (ArrayList<?>) super.clone();
     68             v.elementData = Arrays.copyOf(elementData, size);
     69             v.modCount = 0;
     70             return v;
     71         } catch (CloneNotSupportedException e) {
     72             // this shouldn't happen, since we are Cloneable
     73             throw new InternalError(e);
     74         }
     75     }
     76 
     77     // 按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。 
     78       由于此列表不维护对返回数组的任何引用,因而它将是“安全的”。
     79      (换句话说,此方法必须分配一个新的数组)。因此,调用者可以自由地修改返回的数组。 
     80       此方法担当基于数组的 API 和基于 collection 的 API 之间的桥梁。
     81     public Object[] toArray() {
     82         return Arrays.copyOf(elementData, size);
     83     }
     84   
     85     public <T> T[] toArray(T[] a) {
     86         if (a.length < size)
     87             // Make a new array of a's runtime type, but my contents:
     88             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
     89         System.arraycopy(elementData, 0, a, 0, size);
     90         if (a.length > size)
     91             a[size] = null;
     92         return a;
     93     }
     94 
     95    //清空列表
     96     public void clear() {
     97         modCount++;
     98 
     99         // clear to let GC do its work
    100         for (int i = 0; i < size; i++)
    101             elementData[i] = null;
    102 
    103         size = 0;
    104     }
    105 
    106     //删除fromIndex(包含)到toIndex(不包含)之间的元素
    107     protected void removeRange(int fromIndex, int toIndex) {
    108         modCount++;
    109         int numMoved = size - toIndex;
    110         System.arraycopy(elementData, toIndex, elementData, fromIndex,
    111                          numMoved);
    112 
    113         // clear to let GC do its work
    114         int newSize = size - (toIndex-fromIndex);
    115         for (int i = newSize; i < size; i++) {
    116             elementData[i] = null;
    117         }
    118         size = newSize;
    119     }
    120 
    121     //检测脚标是否越界
    122     private void rangeCheck(int index) {
    123         if (index >= size)
    124             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    125     }
    126 
    127     private String outOfBoundsMsg(int index) {
    128         return "Index: "+index+", Size: "+size;
    129     }
    130 
    131      */
    132     //移除与集合c里相同的元素 
    133     public boolean removeAll(Collection<?> c) {
    134         Objects.requireNonNull(c);
    135         return batchRemove(c, false);
    136     }
    137     
    138     //保留与集合c里相同的元素    
    139     public boolean retainAll(Collection<?> c) {
    140         Objects.requireNonNull(c);
    141         return batchRemove(c, true);
    142     }
    143 
    144     private boolean batchRemove(Collection<?> c, boolean complement) {
    145         final Object[] elementData = this.elementData;
    146         int r = 0, w = 0;
    147         boolean modified = false;
    148         try {
    149             for (; r < size; r++)
    150                 if (c.contains(elementData[r]) == complement)
    151                     elementData[w++] = elementData[r];
    152         } finally {
    153             // Preserve behavioral compatibility with AbstractCollection,
    154             // even if c.contains() throws.
    155             if (r != size) {
    156                 System.arraycopy(elementData, r,
    157                                  elementData, w,
    158                                  size - r);
    159                 w += size - r;
    160             }
    161             if (w != size) {
    162                 // clear to let GC do its work
    163                 for (int i = w; i < size; i++)
    164                     elementData[i] = null;
    165                 modCount += size - w;
    166                 size = w;
    167                 modified = true;
    168             }
    169         }
    170         return modified;
    171     }
    172 
    173     //序列化列表
    174     private void writeObject(java.io.ObjectOutputStream s)
    175         throws java.io.IOException{
    176         // Write out element count, and any hidden stuff
    177         int expectedModCount = modCount;
    178         s.defaultWriteObject();
    179 
    180         // Write out size as capacity for behavioural compatibility with clone()
    181         s.writeInt(size);
    182 
    183         // Write out all elements in the proper order.
    184         for (int i=0; i<size; i++) {
    185             s.writeObject(elementData[i]);    //ArrayList的设计者将elementData设计为transient,
    186             然后在writeObject方法中手动将其序列化,并且只序列化了实际存储的那些元素,而不是整个数组。
    187         }
    188 
    189         if (modCount != expectedModCount) {
    190             throw new ConcurrentModificationException();
    191         }
    192     }
    193 
    194     //反序列化列表 
    195     private void readObject(java.io.ObjectInputStream s)
    196         throws java.io.IOException, ClassNotFoundException {
    197         elementData = EMPTY_ELEMENTDATA;
    198 
    199         // Read in size, and any hidden stuff
    200         s.defaultReadObject();
    201 
    202         // Read in capacity
    203         s.readInt(); // ignored
    204 
    205         if (size > 0) {
    206             // be like clone(), allocate array based upon size not capacity
    207             ensureCapacityInternal(size);
    208 
    209             Object[] a = elementData;
    210             // Read in all elements in the proper order.
    211             for (int i=0; i<size; i++) {
    212                 a[i] = s.readObject();
    213             }
    214         }
    215     }

    Iterator<E> iterator(),ListIterator<E> listIterator(int index) 与LinkedList类似:可参考  https://www.cnblogs.com/sqy123/p/9272666.html

    还有Spliterator 

      1     public Iterator<E> iterator() {
      2         return new Itr();
      3     }
      4 
      5     private class Itr implements Iterator<E> {
      6         int cursor;       // index of next element to return
      7         int lastRet = -1; // index of last element returned; -1 if no such
      8         int expectedModCount = modCount;
      9 
     10         public boolean hasNext() {
     11             return cursor != size;
     12         }
     13 
     14         @SuppressWarnings("unchecked")
     15         public E next() {
     16             checkForComodification();
     17             int i = cursor;
     18             if (i >= size)
     19                 throw new NoSuchElementException();
     20             Object[] elementData = ArrayList.this.elementData;
     21             if (i >= elementData.length)
     22                 throw new ConcurrentModificationException();
     23             cursor = i + 1;
     24             return (E) elementData[lastRet = i];
     25         }
     26 
     27         public void remove() {
     28             if (lastRet < 0)
     29                 throw new IllegalStateException();
     30             checkForComodification();
     31 
     32             try {
     33                 ArrayList.this.remove(lastRet);
     34                 cursor = lastRet;
     35                 lastRet = -1;
     36                 expectedModCount = modCount;
     37             } catch (IndexOutOfBoundsException ex) {
     38                 throw new ConcurrentModificationException();
     39             }
     40         }
     41 
     42         //外部结构修改则迭代快速失败fast-fails
     43         @Override
     44         @SuppressWarnings("unchecked")
     45         public void forEachRemaining(Consumer<? super E> consumer) {
     46             Objects.requireNonNull(consumer);
     47             final int size = ArrayList.this.size;
     48             int i = cursor;
     49             if (i >= size) {
     50                 return;
     51             }
     52             final Object[] elementData = ArrayList.this.elementData;
     53             if (i >= elementData.length) {
     54                 throw new ConcurrentModificationException();
     55             }
     56             while (i != size && modCount == expectedModCount) {
     57                 consumer.accept((E) elementData[i++]);
     58             }
     59             // update once at end of iteration to reduce heap write traffic
     60             cursor = i;
     61             lastRet = i - 1;
     62             checkForComodification();
     63         }
     64 
     65         final void checkForComodification() {
     66             if (modCount != expectedModCount)
     67                 throw new ConcurrentModificationException();
     68         }
     69     }
     70 
     71      //返回此列表中的元素的列表迭代器(按适当顺序:从列表中指定位置开始)
     72     public ListIterator<E> listIterator(int index) {
     73         if (index < 0 || index > size)
     74             throw new IndexOutOfBoundsException("Index: "+index);
     75         return new ListItr(index); //调用内部类ListItr的匿名对象
     76     }
     77 
     78     public ListIterator<E> listIterator() {
     79         return new ListItr(0);
     80     }
     81     
     82     private class ListItr extends Itr implements ListIterator<E> {
     83         ListItr(int index) {
     84             super();
     85             cursor = index;
     86         }
     87 
     88         public boolean hasPrevious() {
     89             return cursor != 0;
     90         }
     91 
     92         public int nextIndex() {
     93             return cursor;
     94         }
     95 
     96         public int previousIndex() {
     97             return cursor - 1;
     98         }
     99 
    100         @SuppressWarnings("unchecked")
    101         public E previous() {
    102             checkForComodification();
    103             int i = cursor - 1;
    104             if (i < 0)
    105                 throw new NoSuchElementException();
    106             Object[] elementData = ArrayList.this.elementData;
    107             if (i >= elementData.length)
    108                 throw new ConcurrentModificationException();
    109             cursor = i;
    110             return (E) elementData[lastRet = i];
    111         }
    112 
    113         public void set(E e) {
    114             if (lastRet < 0)
    115                 throw new IllegalStateException();
    116             checkForComodification();
    117 
    118             try {
    119                 ArrayList.this.set(lastRet, e);
    120             } catch (IndexOutOfBoundsException ex) {
    121                 throw new ConcurrentModificationException();
    122             }
    123         }
    124 
    125         public void add(E e) {
    126             checkForComodification();
    127 
    128             try {
    129                 int i = cursor;
    130                 ArrayList.this.add(i, e);
    131                 cursor = i + 1;
    132                 lastRet = -1;
    133                 expectedModCount = modCount;
    134             } catch (IndexOutOfBoundsException ex) {
    135                 throw new ConcurrentModificationException();
    136             }
    137         }
    138     }
     List<E> subList(int fromIndex, int toIndex):

    对原来的list和返回的sublist做的“非结构性修改”(non-structural changes),都会影响到彼此对方。

       所谓的“非结构性修改”,是指不涉及到list的大小改变的修改。相反,结构性修改,指改变了list大小的修改。

    博文链接:https://blog.csdn.net/leisurelen/article/details/51174614
      1     //获取子列表(包括fromIndex,不包括toIndex)
      2     public List<E> subList(int fromIndex, int toIndex) {
      3         subListRangeCheck(fromIndex, toIndex, size);
      4         return new SubList(this, 0, fromIndex, toIndex);
      5     }
      6 
      7     static void subListRangeCheck(int fromIndex, int toIndex, int size) {
      8         if (fromIndex < 0)
      9             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
     10         if (toIndex > size)
     11             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
     12         if (fromIndex > toIndex)
     13             throw new IllegalArgumentException("fromIndex(" + fromIndex +
     14                                                ") > toIndex(" + toIndex + ")");
     15     }
     16 
     17     private class SubList extends AbstractList<E> implements RandomAccess {
     18         private final AbstractList<E> parent;
     19         private final int parentOffset;
     20         private final int offset;
     21         int size;
     22 
     23         SubList(AbstractList<E> parent,
     24                 int offset, int fromIndex, int toIndex) {
     25             this.parent = parent;
     26             this.parentOffset = fromIndex;
     27             this.offset = offset + fromIndex;
     28             this.size = toIndex - fromIndex;
     29             this.modCount = ArrayList.this.modCount;
     30         }
     31 
     32         public E set(int index, E e) {
     33             rangeCheck(index);
     34             checkForComodification();
     35             E oldValue = ArrayList.this.elementData(offset + index);
     36             ArrayList.this.elementData[offset + index] = e;
     37             return oldValue;
     38         }
     39 
     40         public E get(int index) {
     41             rangeCheck(index);
     42             checkForComodification();
     43             return ArrayList.this.elementData(offset + index);
     44         }
     45 
     46         public int size() {
     47             checkForComodification();
     48             return this.size;
     49         }
     50 
     51         public void add(int index, E e) {
     52             rangeCheckForAdd(index);
     53             checkForComodification();
     54             parent.add(parentOffset + index, e);
     55             this.modCount = parent.modCount;
     56             this.size++;
     57         }
     58 
     59         public E remove(int index) {
     60             rangeCheck(index);
     61             checkForComodification();
     62             E result = parent.remove(parentOffset + index);
     63             this.modCount = parent.modCount;
     64             this.size--;
     65             return result;
     66         }
     67 
     68         protected void removeRange(int fromIndex, int toIndex) {
     69             checkForComodification();
     70             parent.removeRange(parentOffset + fromIndex,
     71                                parentOffset + toIndex);
     72             this.modCount = parent.modCount;
     73             this.size -= toIndex - fromIndex;
     74         }
     75 
     76         public boolean addAll(Collection<? extends E> c) {
     77             return addAll(this.size, c);
     78         }
     79 
     80         public boolean addAll(int index, Collection<? extends E> c) {
     81             rangeCheckForAdd(index);
     82             int cSize = c.size();
     83             if (cSize==0)
     84                 return false;
     85 
     86             checkForComodification();
     87             parent.addAll(parentOffset + index, c);
     88             this.modCount = parent.modCount;
     89             this.size += cSize;
     90             return true;
     91         }
     92 
     93         public Iterator<E> iterator() {
     94             return listIterator();
     95         }
     96 
     97         public ListIterator<E> listIterator(final int index) {
     98             checkForComodification();
     99             rangeCheckForAdd(index);
    100             final int offset = this.offset;
    101 
    102             return new ListIterator<E>() {
    103                 int cursor = index;
    104                 int lastRet = -1;
    105                 int expectedModCount = ArrayList.this.modCount;
    106 
    107                 public boolean hasNext() {
    108                     return cursor != SubList.this.size;
    109                 }
    110 
    111                 @SuppressWarnings("unchecked")
    112                 public E next() {
    113                     checkForComodification();
    114                     int i = cursor;
    115                     if (i >= SubList.this.size)
    116                         throw new NoSuchElementException();
    117                     Object[] elementData = ArrayList.this.elementData;
    118                     if (offset + i >= elementData.length)
    119                         throw new ConcurrentModificationException();
    120                     cursor = i + 1;
    121                     return (E) elementData[offset + (lastRet = i)];
    122                 }
    123 
    124                 public boolean hasPrevious() {
    125                     return cursor != 0;
    126                 }
    127 
    128                 @SuppressWarnings("unchecked")
    129                 public E previous() {
    130                     checkForComodification();
    131                     int i = cursor - 1;
    132                     if (i < 0)
    133                         throw new NoSuchElementException();
    134                     Object[] elementData = ArrayList.this.elementData;
    135                     if (offset + i >= elementData.length)
    136                         throw new ConcurrentModificationException();
    137                     cursor = i;
    138                     return (E) elementData[offset + (lastRet = i)];
    139                 }
    140 
    141                 @SuppressWarnings("unchecked")
    142                 public void forEachRemaining(Consumer<? super E> consumer) {
    143                     Objects.requireNonNull(consumer);
    144                     final int size = SubList.this.size;
    145                     int i = cursor;
    146                     if (i >= size) {
    147                         return;
    148                     }
    149                     final Object[] elementData = ArrayList.this.elementData;
    150                     if (offset + i >= elementData.length) {
    151                         throw new ConcurrentModificationException();
    152                     }
    153                     while (i != size && modCount == expectedModCount) {
    154                         consumer.accept((E) elementData[offset + (i++)]);
    155                     }
    156                     // update once at end of iteration to reduce heap write traffic
    157                     lastRet = cursor = i;
    158                     checkForComodification();
    159                 }
    160 
    161                 public int nextIndex() {
    162                     return cursor;
    163                 }
    164 
    165                 public int previousIndex() {
    166                     return cursor - 1;
    167                 }
    168 
    169                 public void remove() {
    170                     if (lastRet < 0)
    171                         throw new IllegalStateException();
    172                     checkForComodification();
    173 
    174                     try {
    175                         SubList.this.remove(lastRet);
    176                         cursor = lastRet;
    177                         lastRet = -1;
    178                         expectedModCount = ArrayList.this.modCount;
    179                     } catch (IndexOutOfBoundsException ex) {
    180                         throw new ConcurrentModificationException();
    181                     }
    182                 }
    183 
    184                 public void set(E e) {
    185                     if (lastRet < 0)
    186                         throw new IllegalStateException();
    187                     checkForComodification();
    188 
    189                     try {
    190                         ArrayList.this.set(offset + lastRet, e);
    191                     } catch (IndexOutOfBoundsException ex) {
    192                         throw new ConcurrentModificationException();
    193                     }
    194                 }
    195 
    196                 public void add(E e) {
    197                     checkForComodification();
    198 
    199                     try {
    200                         int i = cursor;
    201                         SubList.this.add(i, e);
    202                         cursor = i + 1;
    203                         lastRet = -1;
    204                         expectedModCount = ArrayList.this.modCount;
    205                     } catch (IndexOutOfBoundsException ex) {
    206                         throw new ConcurrentModificationException();
    207                     }
    208                 }
    209 
    210                 final void checkForComodification() {
    211                     if (expectedModCount != ArrayList.this.modCount)
    212                         throw new ConcurrentModificationException();
    213                 }
    214             };
    215         }
    216 
    217         public List<E> subList(int fromIndex, int toIndex) {
    218             subListRangeCheck(fromIndex, toIndex, size);
    219             return new SubList(this, offset, fromIndex, toIndex);
    220         }
    221 
    222         private void rangeCheck(int index) {
    223             if (index < 0 || index >= this.size)
    224                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    225         }
    226 
    227         private void rangeCheckForAdd(int index) {
    228             if (index < 0 || index > this.size)
    229                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    230         }
    231 
    232         private String outOfBoundsMsg(int index) {
    233             return "Index: "+index+", Size: "+this.size;
    234         }
    235 
    236         private void checkForComodification() {
    237             if (ArrayList.this.modCount != this.modCount)
    238                 throw new ConcurrentModificationException();
    239         }
    240 
    241         public Spliterator<E> spliterator() {
    242             checkForComodification();
    243             return new ArrayListSpliterator<E>(ArrayList.this, offset,
    244                                                offset + this.size, this.modCount);
    245         }
    246     }
    void sort(Comparator<? super E> c):比较
     1   @Override
     2     @SuppressWarnings("unchecked")
     3     //使用自定义比较器进行排序
     4     public void sort(Comparator<? super E> c) {
     5         final int expectedModCount = modCount;
     6         Arrays.sort((E[]) elementData, 0, size, c);
     7         if (modCount != expectedModCount) {
     8             throw new ConcurrentModificationException();
     9         }
    10         modCount++;
    11     }

    demo:

     1     public static void main(String[] args) {
     2         ArrayList<Integer> list = new ArrayList<>();
     3         list.add(1);
     4         list.add(3);
     5         list.add(7);
     6         list.add(0);
     7 
     8         Comparator c = new Comparator<Integer>() {
     9             @Override
    10             public int compare(Integer o1, Integer o2) {
    11                 // TODO Auto-generated method stub
    12                 if((int)o1<(int)o2)
    13                     return 1;
    14                     //注意!!返回值必须是一对相反数,否则无效。jdk1.7以后就是这样。
    15                     //        else return 0; //无效
    16                 else return -1;
    17             }
    18         };
    19         System.out.println("原始:"+list);
    20         list.sort(c);
    21         System.out.println("排序后:"+list);
    22     }

    结果:

    1 原始:[1, 3, 7, 0]
    2 排序后:[7, 3, 1, 0]

    void forEach(Consumer<? super E> action) :

     1    @Override
     2     public void forEach(Consumer<? super E> action) {
     3         Objects.requireNonNull(action);
     4         final int expectedModCount = modCount;
     5         @SuppressWarnings("unchecked")
     6         final E[] elementData = (E[]) this.elementData;
     7         final int size = this.size;
     8         for (int i=0; modCount == expectedModCount && i < size; i++) {
     9             action.accept(elementData[i]);
    10         }
    11         if (modCount != expectedModCount) {
    12             throw new ConcurrentModificationException();
    13         }
    14     }

    demo:

     1 public static void main(String[] args) {
     2         ArrayList<Integer> list = new ArrayList<>();
     3         list.add(1);
     4         list.add(3);
     5         list.add(7);
     6         list.add(0);
     7         list.forEach(new Consumer<Integer>() {
     8 
     9                  @Override
    10                  public void accept(Integer str) {
    11                      if (str > 3)
    12                          System.out.println(str);
    13                  }
    14              }
    15         );
    16         System.out.println(list);
    17     }

    结果:

    7
    [1, 3, 7, 0]

    也可以写成lamb表达式,这样更简洁,

     1  public static void main(String[] args) {
     2         ArrayList<Integer> list = new ArrayList<>();
     3         list.add(1);
     4         list.add(3);
     5         list.add(7);
     6         list.add(0);
     7         list.forEach(str -> {
     8                 if (str > 3)
     9                     System.out.println(str);
    10             }
    11         );
    12         System.out.println(list);
    13     }

    同理  void replaceAll(UnaryOperator<E> operator),boolean removeIf(Predicate<? super E> filter) 引用博文:https://www.cnblogs.com/CarpenterLee/p/6507161.html

     1  @Override
     2     @SuppressWarnings("unchecked")
     3     public void replaceAll(UnaryOperator<E> operator) {
     4         Objects.requireNonNull(operator);
     5         final int expectedModCount = modCount;
     6         final int size = this.size;
     7         for (int i=0; modCount == expectedModCount && i < size; i++) {
     8             elementData[i] = operator.apply((E) elementData[i]);
     9         }
    10         if (modCount != expectedModCount) {
    11             throw new ConcurrentModificationException();
    12         }
    13         modCount++;
    14     }
  • 相关阅读:
    java Class的 getSuperclass与getGenericSuperclass区别
    再有人问你volatile是什么,把这篇文章也发给他
    深入理解乐观锁与悲观锁
    再有人问你Java内存模型是什么,就把这篇文章发给他
    再有人问你synchronized是什么,就把这篇文章发给他
    《成神之路-基础篇》JVM——Java内存模型(已完结)
    css
    css
    require.js
    css -border
  • 原文地址:https://www.cnblogs.com/sqy123/p/9341027.html
Copyright © 2020-2023  润新知