1. 程式人生 > >7、集合--ArrayList的測試以及相關方法的源碼解析

7、集合--ArrayList的測試以及相關方法的源碼解析

leg protected cati ide swa ansi class bject cte

ArrayList的測試

public static void main(String[] args) {

        List list = new ArrayList();

        list.add("1");
        list.add("2");
        list.add("3");
        list.add("a");
        list.add("a");
        list.add("b");
        System.out.println(list);
        System.out
.println("長度:" + list.size()); //遍歷 for (int i = 0; i < list.size();i++){ Object obj = list.get(i); System.out.println("for循環遍歷list:" + obj); } //叠代器遍歷 Iterator it = list.iterator(); while (it.hasNext()){ System.
out.println("叠代器遍歷list:" + it.next()); } //在指定位置添加數據 list.add(0,"news"); System.out.println("指定0位置的數據:" + list.get(0)); //替代指定位置上的元素 list.set(0,"old"); System.out.println("替代0位置的元素:" + list.get(0)); //獲取第一次出現元素a的位置 System.out
.println("元素a第一次出現的位置:" + list.indexOf("a") ); //獲取最後一次出現元素a的位置 System.out.println("元素a第一次出現的位置:" + list.lastIndexOf("a")); //移除指定位置上的元素 list.remove(0); System.out.println("第一個元素:" + list.get(0)); //清空集合 list.clear(); }

技術分享圖片

相關方法的解析:

在new ArrayList之後:

底層的實現是數組

size用於確定此時操作的位數

  transient Object[] elementData;
  private int size;
  protected transient int modCount = 0;//用來叠代操作的數據
  private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

add(E e)方法

在數組中進行添加是size會自增,將數據存放在數組中

此時會返回true

同時會執行一下相關的方法

    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) {
  minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
   }
   ensureExplicitCapacity(minCapacity);
  }
  private void ensureCapacityInternal(int minCapacity) {
  if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
      minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  }
   ensureExplicitCapacity(minCapacity);
  }
  private void ensureExplicitCapacity(int minCapacity) {
   modCount++;
   // overflow-conscious code
   if (minCapacity - elementData.length > 0)
   grow(minCapacity);
  }
  private void grow(int minCapacity) {
   // overflow-conscious code
   int oldCapacity = elementData.length;
   int newCapacity = oldCapacity + (oldCapacity >> 1);
   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);
}

add(int index,E e)方法

首先檢查index是否有誤

然後執行System.arraycopy(elementData, index, elementData, index + 1,size - index);進行復制數組

將index位置空出,在進行在elementDate【index】位置上設置數據


    public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1); // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
   size - index);
     elementData[index] = element;
     size++;
    }  
    private void rangeCheckForAdd(int index) {
     if (index < 0 || index > this.size)
     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private void ensureCapacityInternal(int minCapacity) {
     if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
     minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
   }
     ensureExplicitCapacity(minCapacity);
    }
    ......

size()方法

此時返回的是size數值

public int size() {
        return size;
    }

get()方法

首先會對傳入的索引值進行判斷

如果索引值小於index則會拋出異常

否則將會返回數組指定索引的值

  public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }
  private void rangeCheck(int index) {
   if (index >= size)
   throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  }

iterator()方法

會返回一個Itr對象

Itr對象中會有hasNext()、next()方法

此時的操作需要註意的是數據:modCount

在之前的操作中modCount的數據處於自增狀態

    public Iterator<E> iterator() {
        return new 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();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @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();
        }
    }

set(int index,E element)方法

用於修改指定位置的元素值

首先調用rangeCheck(index)來判斷索引值是否越界

將之前的值進行保存

將需要改的值設置在指定索引的位置

最後返回舊值(舊值可能需要)

public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

  private void rangeCheck(int index) {
   if (index >= size)
  throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  }

IndexOf(Object o)方法

首先判斷其值是否為null

如果為null在依次進行循環判斷,返值為i,此時的i則是第一次出現的位置

如果不為空在進行判斷

此時使用equals()方法和數組中的每一個值進行判斷

返回第一次相同的位置,返回此時的索引值為i

如果都沒有則返回-1

public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

lastIndexOf(Object o)方法

此時的判斷方法和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;
    }

clear()方法

遍歷數組,將索引值都置為null

並且將size的值置為0

public void clear() {
        modCount++;
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

remove(int index)刪除指定索引位置的元素

首先調用rangeCheck()方法來檢測index是否有越界錯誤

在調用System.array()方法進行復制數組

在讓size自減並且將最後的一個值設置為null

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;
    }

  private void rangeCheck(int index) {
   if (index >= size)
  throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  }

remove(Object o)刪除指定的對象

首先將傳入的對象和null進行對比

如果未null則進行遍歷在進行調用fastRemove(int index)方法

如果傳入的對象不為null

則使用equals()方法進行判斷兩個對象是相同,在調用fastRemove()fangfa

如果以上都不滿足,返回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++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

  private void fastRemove(int index) {
   modCount++;
   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
}
 

removeAll(Collection<?> c)從集合中刪除集合c中包含的元素

此時依次調用requireNonNull()方法

在此調用batchRemove()方法

  public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

  public static <T> T requireNonNull(T obj) {
   if (obj == null)
   throw new NullPointerException();
   return obj;
  }

  private boolean batchRemove(Collection<?> c, boolean complement) {
   final Object[] elementData = this.elementData;
   int r = 0, w = 0;
   boolean modified = false;
   try {
   for (; r < size; r++)
   if (c.contains(elementData[r]) == complement)
   elementData[w++] = elementData[r];
   } finally {
   // Preserve behavioral compatibility with AbstractCollection,
   // even if c.contains() throws.
   if (r != size) {
   System.arraycopy(elementData, r,
   elementData, w,
   size - r);
   w += size - r;
   }
   if (w != size) {
  // clear to let GC do its work
   for (int i = w; i < size; i++)
   elementData[i] = null;
   modCount += size - w;
   size = w;
   modified = true;
    }
   }
   return modified;
  }

contains(Object o)集合中是都包含元o

會返回indexOf(Object o)方法進行返回值的設置

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }


   public int indexOf(Object o) {
          if (o == null) {
              for (int i = 0; i < size; i++)
                  if (elementData[i]==null)
                      return i;
          } else {
              for (int i = 0; i < size; i++)
                  if (o.equals(elementData[i]))
                      return i;
          }
          return -1;
      }

isEmpty()方法測試數組是否為空

public boolean isEmpty() {
        return size == 0;
    }

對於ArrayList的基本方法分析到此結束

...............................................

7、集合--ArrayList的測試以及相關方法的源碼解析