博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
7、集合--ArrayList的测试以及相关方法的源码解析
阅读量:7136 次
发布时间:2019-06-28

本文共 11565 字,大约阅读时间需要 38 分钟。

 

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
iterator() { return new Itr(); } private class Itr implements Iterator
{ 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
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 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的基本方法分析到此结束

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

 

转载于:https://www.cnblogs.com/Mrchengs/p/10846853.html

你可能感兴趣的文章
编译安装MySQL5.5
查看>>
我的友情链接
查看>>
利用NFS/SAMBA构建网络wordpress
查看>>
Java网络编程之TCP通信
查看>>
剑指offer:青蛙跳台阶
查看>>
linux下重启mysql(更新0908)
查看>>
Eclipse安装PyDev插件以及常用设置
查看>>
CCNP第四天
查看>>
Python suds模块测试WebSerivce服务和Type not found错误解决
查看>>
dsh批量管理linux服务器
查看>>
解析IT运维管理软件七大管理内容
查看>>
VC平台Miracl编译及使用
查看>>
百度网盘资源搜索
查看>>
学习日志---图之最小生成树算法
查看>>
基于虚拟帐号的邮件系统(extmail)上
查看>>
互联网你怎么了?
查看>>
我的友情链接
查看>>
修改python文件编码格式
查看>>
在linux客户端下管理svn版本库
查看>>
开源高手推荐十大最流行开源软件
查看>>