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

本文深入解析了Java中ArrayList的数据结构及其实现原理,包括其内部使用的Object数组、关键属性及构造函数,同时还介绍了如size、isEmpty、contains等常用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


public classArrayList<E> extends AbstractList<E>
       implementsList<E>, 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<? extends E> 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等方法了。下一篇博客来介绍。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值