IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]Java集合类源代码分析二:ArrayList(1)

    lfsf802发表于 2015-01-28 21:20:56
    love 0

    从java集合结构能够看出来ArrayList是属于Collection中的List范畴的。从源代码中是这样表示的,


    public classArrayList extends AbstractList
           implementsList, RandomAccess, Cloneable, java.io.Serializable
     


    ArrayList有两个属性:

    /**
         * The array buffer into which the elementsof the ArrayList are stored.
         * The capacity of the ArrayList is thelength of this array buffer.
         */
       privatetransientObject[] elementData;
     
       /**
         * The size of the ArrayList (the number ofelements it contains).
         *
         * @serial
         */
    private int size;


    从两个属性能够看出来ArrayList的数据结构是Object数组。这里的Object数组是transient来修饰的,针对这个关键字的介绍参见博客《java的transient关键字》。

    ArrayList有三个构造函数:

       publicArrayList(intinitialCapacity) {
            super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("IllegalCapacity: "+
                                                  initialCapacity);
            this.elementData= newObject[initialCapacity];
       }
     
        public ArrayList() {
            this(10);
       }
        publicArrayList(Collection c) {
            elementData = c.toArray();
            size = elementData.length;
            // c.toArraymight (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass()!= Object[].class)
                elementData = Arrays.copyOf(elementData, size,Object[].class);
    }
    }


    第一个构造函数传入一个数组长度,以此来实例化Object数组,第二个构造函数默认实例化Object数组的长度为10,第三个构造函数是传入一个Collection集合,将集合转换为数组赋给Object数组,长度赋给size,如果此时传入的集合的类型不是Object类型的话就通过数组拷贝的方法将类型转换成Object类型。

    下面来看几个关键的方法:

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


    这三个方法比较简单,区size值和判断是否是空以及判断是否包含某个对象。

    在最后一个方法中涉及到了indexOf方法:


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



    这个方法是针对数组进行遍历,如果存在则返回索引值,如果没有发现则返回-1。

    后面还有toArray方法和clone方法以及lastIndexOf,简单介绍一下源代码,首先toArray主要是通过Arrays.copyof方法将数组和集合建立一个桥梁,clone方法就是拷贝,这里注意是浅拷贝方法,lastIndexOf是从后面进行索引,这个与indexOf正好相反。

    后面就是经常用的get、set、add、remove等方法了。下一篇博客来介绍。



沪ICP备19023445号-2号
友情链接