美文网首页
Java集合框架(三)— ArrayList

Java集合框架(三)— ArrayList

作者: Sandy_678f | 来源:发表于2018-12-02 20:46 被阅读0次
    image.png

    ArrayList定义

    public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
    

    ArrayList继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。

    ArrayList 实现了RandomAccess接口,即提供了随机访问功能。RandomAccess是java中用来被List实现,为List提供快速访问功能的。

    ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。

    ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。

    ArrayList中的操作不是线程安全的!//TODO

    ArrayList的API

    // Collection中定义的API
    boolean             add(E object)
    boolean             addAll(Collection<? extends E> collection)
    void                clear()
    boolean             contains(Object object)
    boolean             containsAll(Collection<?> collection)
    boolean             equals(Object object)
    int                 hashCode()
    boolean             isEmpty()
    Iterator<E>         iterator()
    boolean             remove(Object object)
    boolean             removeAll(Collection<?> collection)
    boolean             retainAll(Collection<?> collection)
    int                 size()
    <T> T[]             toArray(T[] array)
    Object[]            toArray()
    
    // List新增的API
    void                add(int location, E object)
    boolean             addAll(int location, Collection<? extends E> collection)
    E                   get(int location)
    int                 indexOf(Object object)
    int                 lastIndexOf(Object object)
    ListIterator<E>     listIterator(int location)
    ListIterator<E>     listIterator()
    E                   remove(int location)
    E                   set(int location, E object)
    List<E>             subList(int start, int end)
    
    // ArrayList新增的API
    Object               clone()
    void                 ensureCapacity(int minimumCapacity)
    void                 trimToSize()
    void                 removeRange(int fromIndex, int toIndex)
    

    ArrayList包含了两个重要的对象:elementData 和 size。

    (01) elementData 是"Object[]类型的数组",它保存了添加到ArrayList中的元素。实际上,elementData是个动态数组,我们能通过构造函数 ArrayList(int initialCapacity)来执行它的初始容量为initialCapacity;如果通过不含参数的构造函数ArrayList()来创建ArrayList,则elementData的容量默认是10。elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体的增长方式,请参考源码分析中的ensureCapacity()函数。elementData用transient修饰,不被序列化。

    (02) size 则是动态数组的实际大小。

    ArrayList的三种构造函数

     public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
            }
        }
    
    public ArrayList() {
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
        }
    
     public ArrayList(Collection<? extends E> c) {
            elementData = c.toArray();
            if ((size = elementData.length) != 0) {
                // c.toArray might (incorrectly) not return Object[] (see 6260652)
                if (elementData.getClass() != Object[].class)
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
            } else {
                // replace with empty array.
                this.elementData = EMPTY_ELEMENTDATA;
            }
        }
    

    ArrayList的三种遍历方式

    /**
     * FileName: ArrayListIterator
     * Author:   Sandy
     * Date:     2018/12/2 16:49
     * Description: ArrayList遍历方式及其比较
     * Version: v1.0.0
     */
    
    package ArrayListDemo;
    
    import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
    
    import java.io.ObjectInputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class ArrayListIterator {
    
        public static void iteratorArrayListByIterator(ArrayList arrayList){
    
            long startTime;
            long endTime;
    
            Iterator iterator = arrayList.iterator();
            startTime = System.currentTimeMillis();
            while(iterator.hasNext()){
                iterator.next();
            }
            endTime = System.currentTimeMillis();
            long interval = endTime - startTime;
            System.out.println("通过迭代器遍历ArrayList效率为:" + interval);
    
        }
    
        public static void iteratorArrayListByRondomAccess(ArrayList arrayList){
    
            long startTime;
            long endTime;
    
            Object value;
    
            startTime = System.currentTimeMillis();
            for (int i = 0; i < arrayList.size(); i++){
                value = arrayList.get(i);
            }
            endTime = System.currentTimeMillis();
    
            long interval = endTime - startTime;
            System.out.println("通过随机访问遍历ArrayList效率为:" + interval);
        }
    
        public static void iteratorArrayListByFor(ArrayList arrayList){
    
            long startTime;
            long endTime;
    
            Object value;
    
            startTime = System.currentTimeMillis();
            for(Object object : arrayList){
                value = object;
            }
            endTime = System.currentTimeMillis();
    
            long interval = endTime - startTime;
            System.out.println("通过For循环遍历ArrayList效率为:" + interval);
        }
    
        public static void main(String[] args) {
    
            ArrayList arrayList = new ArrayList();
            for(int i = 0; i < 10000; i++){
                arrayList.add(i);
            }
    
            //效率对比
            iteratorArrayListByIterator(arrayList);
            iteratorArrayListByRondomAccess(arrayList);
            iteratorArrayListByFor(arrayList);
    
        }
    }
    

    输出:

    通过迭代器遍历ArrayList效率为:9
    通过索引值遍历ArrayList效率为:8796
    通过For循环遍历ArrayList效率为:7
    

    ArrayList应用

    package ArrayListDemo;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    
    /**
     * @ClassName: ArrayListDemo
     * @Author sandy.n.hao
     * @Date: 2018/12/10
     * @Version v1.0.0
     * @Description: //TODO
     */
    
    public class ArrayListDemo {
    
        public static void main(String[] args) {
    
            String [] data = new String[] {"abc","def","ghi"};
    
            ArrayList arrayList1 = new ArrayList() {
                {
                    //调用ArrayList的add()方法,add方法检查是否需要扩容,并且修改modCount+1,增加元素
                    add("abc");
                    add(123);
                    add("def");
                    add(456);
                }
            };
            ArrayList arrayList2 = new ArrayList(Arrays.asList(data));
    
            //List的并集,不排除重复
            arrayList2.addAll(arrayList1);
            System.out.println(arrayList2);
    
            //List的交集,不排除重复
    //        arrayList2.retainAll(arrayList1);
    //        System.out.println(arrayList2);
    
            //List的差集,不排除重复
    //        arrayList2.removeAll(arrayList1);
    //        System.out.println(arrayList2);
        }
    
    }
    

    输出:

    并集:[abc, def, ghi, abc, 123, def, 456]
    
    交集:[abc, def]
    
    差集:[ghi]
    

    相关文章

      网友评论

          本文标题:Java集合框架(三)— ArrayList

          本文链接:https://www.haomeiwen.com/subject/eaajcqtx.html