zoukankan      html  css  js  c++  java
  • 集合框架(四)

    常用Collection之ArrayList

    一、继承关系

    AbstractCollection<—AbstractList<—ArrayList
    

    二、原理

    transient Object[] elementData; //elementData用来存放数据	
    
    底层是用array实现完成的	
    

    三、构造方法

    public ArrayList(int initialCapacity);//创建一个初始容量为initialCapacity的Object数组
    
    public ArrayList();//创建一个初始容量为10的Object数组(调用构造方法时,仅仅创建一个空数组,调用add方法时重新创建数组,数组长度为默认值10)  
    
    public ArrayList(Collection<? extends E> c);//先将c转为数组,并赋值给elementData,然后elementData数组类型向上转型为Object
    

    四、常用方法实现原理

    1、private void grow(int minCapacity);//改变数组长度,起增长方式为每次增加原数组长度的一半{int newCapacity = oldCapacity + (oldCapacity >> 1);}
    
    2、public Object[] toArray();//调用Arrays.copyOf()方法{return Arrays.copyOf(elementData, size);} 
    
    3、public boolean add(E e);//如果元素元素为空,该方法会使得容量最小为10{if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);        }} 
    
    4、public void add(int index, E element);//{System.arraycopy(elementData, index, elementData, index + 1,size - index);}将源数组从index处开始复制到目标(自身)从index+1处开始,然后将index处的值重设为element 
    
    5、public boolean remove(Object o) ;//遍历数组,找到o所在的index,删除index,并调用fastRemove(int index)方法,将index右面的数据整体左移
    
    6、private void fastRemove(int index);//{System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null; }
    
    7、 public Iterator<E> iterator();//{return new Itr();}Itr为内部类 
    

    五、迭代器实现

    注:cursor没有手动设初始值(int型默认值为0,创建对象时,便会进行初始化动作),我一眼看到也是一眼懵逼。	  
    
    hasNext()方法和next()方法还有remove()方法实现原理还是相对简单。  
    
    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();
        }
    }
    

    六、总结

    以array实现完成的List。允许快速访问和随机访问,但当元素的安插或移除发生在List中央位置时,效率很差(从原数组到原数组复制,查看add(index,ele)方法可知)。可以选择ArrayList遍历走访元素,如果有较多的插入和移除动作,最好选择LinkedList(将在"集合框架(六)"中介绍)。
    All rights reserved please indicate the source if reprint---吓尿了的大肥鼠
  • 相关阅读:
    Bandicam班迪录屏 高清录制视频软件
    理解WebKit和Chromium: 浏览器综述
    GDAL对于raw数据支持的一个bug
    关于GDAL计算图像坐标的几个问题
    理解WebKit和Chromium: WebKit资源加载机制
    关于web服务器架构的思考
    使用PROJ4库将地心直角坐标(XYZ)转为地心大地坐标(BLH)
    Java数据类型和MySql数据类型对应表
    理解WebKit和Chromium: 基于Chromium内核的Android WebView
    【Unity探究】物理碰撞实验
  • 原文地址:https://www.cnblogs.com/realsoul/p/5702224.html
Copyright © 2011-2022 走看看