7、集合--ArrayList的测试以及相关方法的源码解析

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的基本方法分析到此结束

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

猜你喜欢

转载自www.cnblogs.com/Mrchengs/p/10846853.html