Java中ArrayList源码深入分析(JDK1.6)

本文详细解读了Java ArrayList类的源码,包括其构造方法、其他方法以及内部属性,如elementData和size,解释了transient关键字的作用,以及add、remove等核心方法的实现原理,帮助开发者更好地理解并应用ArrayList。

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

ArrayList就是传说中的动态数组,就是Array的复杂版本,它提供了如下一些好处:动态的增加和减少元素、灵活的设置数组的大小......

认真阅读本文,我相信一定会对你有帮助。比如为什么ArrayList里面提供了一个受保护的removeRange方法?提供了其他没有被调用过的私有方法?

首先看到对ArrayList的定义:

[java] view plain copy
  1. publicclassArrayList<E>extendsAbstractList<E>implementsList<E>,RandomAccess,Cloneable,java.io.Serializable

从ArrayList<E>可以看出它是支持泛型的,它继承自AbstractList,实现了List、RandomAccess、Cloneable、java.io.Serializable接口

AbstractList提供了List接口的默认实现(个别方法为抽象方法)。

List接口定义了列表必须实现的方法。

RandomAccess是一个标记接口,接口内没有定义任何内容。

实现了Cloneable接口(标记接口,接口内没有定义任何内容)的类,可以调用Object.clone方法返回该对象的浅拷贝。

通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。序列化接口没有方法或字段,仅用于标识可序列化的语义。

ArrayList的属性

ArrayList定义只定义类两个私有属性:

[java] view plain copy
  1. /**
  2. *ThearraybufferintowhichtheelementsoftheArrayListarestored.
  3. *ThecapacityoftheArrayLististhelengthofthisarraybuffer.
  4. */
  5. privatetransientObject[]elementData;
  6. /**
  7. *ThesizeoftheArrayList(thenumberofelementsitcontains).
  8. *@serial
  9. */
  10. privateintsize;
[java] view plain copy
  1. 很容易理解,elementData存储ArrayList内的元素,size表示它包含的元素的数量。
  2. 有个关键字需要解释:transient
  3. Java的serialization提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用serialization机制来保存它。为了在一个特定对象的一个域上关闭serialization,可以在这个域前加上关键字transient
  4. ansient是Java语言的关键字,用来表示一个域不是该对象串行化的一部分。当一个对象被串行化的时候,transient型变量的值不包括在串行化的表示中,然而非transient型的变量是被包括进去的。
  5. 有点抽象,看个例子应该能明白。
[java] view plain copy
  1. publicclassUserInfoimplementsSerializable{
  2. privatestaticfinallongserialVersionUID=996890129747019948L;
  3. privateStringname;
  4. privatetransientStringpsw;
  5. publicUserInfo(Stringname,Stringpsw){
  6. this.name=name;
  7. this.psw=psw;
  8. }
  9. publicStringtoString(){
  10. return"name="+name+",psw="+psw;
  11. }
  12. }
  13. publicclassTestTransient{
  14. publicstaticvoidmain(String[]args){
  15. UserInfouserInfo=newUserInfo("张三","123456");
  16. System.out.println(userInfo);
  17. try{
  18. //序列化,被设置为transient的属性没有被序列化
  19. ObjectOutputStreamo=newObjectOutputStream(newFileOutputStream(
  20. "UserInfo.out"));
  21. o.writeObject(userInfo);
  22. o.close();
  23. }catch(Exceptione){
  24. //TODO:handleexception
  25. e.printStackTrace();
  26. }
  27. try{
  28. //重新读取内容
  29. ObjectInputStreamin=newObjectInputStream(newFileInputStream(
  30. "UserInfo.out"));
  31. UserInforeadUserInfo=(UserInfo)in.readObject();
  32. //读取后psw的内容为null
  33. System.out.println(readUserInfo.toString());
  34. }catch(Exceptione){
  35. //TODO:handleexception
  36. e.printStackTrace();
  37. }
  38. }
  39. }
name=张三, psw=123456
name=张三, psw=null

被标记为transient的属性在对象被序列化的时候不会被保存。

接着回到ArrayList的分析中......

ArrayList的构造方法

看完属性看构造方法。ArrayList提供了三个构造方法:

[java] view plain copy
  1. /**
  2. *Constructsanemptylistwiththespecifiedinitialcapacity.
  3. */
  4. publicArrayList(intinitialCapacity){
  5. super();
  6. if(initialCapacity<0)
  7. thrownewIllegalArgumentException("IllegalCapacity:"+initialCapacity);
  8. this.elementData=newObject[initialCapacity];
  9. }
  10. /**
  11. *Constructsanemptylistwithaninitialcapacityoften.
  12. */
  13. publicArrayList(){
  14. this(10);
  15. }
  16. /**
  17. *Constructsalistcontainingtheelementsofthespecified
  18. *collection,intheordertheyarereturnedbythecollection's
  19. *iterator.
  20. */
  21. publicArrayList(Collection<?extendsE>c){
  22. elementData=c.toArray();
  23. size=elementData.length;
  24. //c.toArraymight(incorrectly)notreturnObject[](see6260652)
  25. if(elementData.getClass()!=Object[].class)
  26. elementData=Arrays.copyOf(elementData,size,Object[].class);
  27. }

     elementData=Arrays.copyOf(elementData,size,Object[].class)
    
      public static <T,U> T[] copyOf(U[]original, intnewLength, Class<? extends T[]>newType)
复制指定的数组,截取或用 null 填充(如有必要),以使副本具有指定的长度。对于在原数组和副本中都有效的所有索引,这两个数组将包含相同的值。对于在副本中有效而在原数组无效的所有索引,副本将包含 null。当且仅当指定长度大于原数组的长度时,这些索引存在。所得数组属于 newType 类。

参数:
original - 要复制的数组
newLength - 要返回的副本的长度
newType - 要返回的副本的类
返回:
原数组的副本,截取或用 null 填充以获得指定的长度


第一个构造方法使用提供的initialCapacity来初始化elementData数组的大小。

第二个构造方法调用第一个构造方法并传入参数10,即默认elementData数组的大小为10。

第三个构造方法则将提供的集合转成数组返回给elementData(返回若不是Object[]将调用Arrays.copyOf方法将其转为Object[])。

ArrayList的其他方法

add(E e)

add(E e)都知道是在尾部添加一个元素,如何实现的呢?

[java] view plain copy
  1. publicbooleanadd(Ee){
  2. ensureCapacity(size+1);//IncrementsmodCount!!
  3. elementData[size++]=e;
  4. returntrue;
  5. }

书上都说ArrayList是基于数组实现的,属性中也看到了数组,具体是怎么实现的呢?

比如就这个添加元素的方法,如果数组大,则在将某个位置的值设置为指定元素即可,如果数组容量不够了呢?

看到add(E e)中先调用了ensureCapacity(size+1)方法,之后将元素的索引赋给elementData[size],而后size自增。

例如初次添加时,size为0,add将elementData[0]赋值为e,然后size设置为1(类似执行以下两条语句elementData[0]=e;size=1)。

将元素的索引赋给elementData[size]不是会出现数组越界的情况吗?这里关键就在ensureCapacity(size+1)中了。

根据ensureCapacity的方法名可以知道是确保容量用的。

ensureCapacity(size+1)后面的注释可以明白是增加modCount的值(加了俩感叹号,应该蛮重要的,来看看)。

[java] view plain copy
  1. /**
  2. *Increasesthecapacityofthis<tt>ArrayList</tt>instance,if
  3. *necessary,toensurethatitcanholdatleastthenumberofelements
  4. *specifiedbytheminimumcapacityargument.
  5. *
  6. *@paramminCapacitythedesiredminimumcapacity
  7. */
  8. publicvoidensureCapacity(intminCapacity){
  9. modCount++;
  10. intoldCapacity=elementData.length;
  11. if(minCapacity>oldCapacity){
  12. ObjectoldData[]=elementData;
  13. intnewCapacity=(oldCapacity*3)/2+1;
  14. if(newCapacity<minCapacity)
  15. newCapacity=minCapacity;
  16. //minCapacityisusuallyclosetosize,sothisisawin:
  17. elementData=Arrays.copyOf(elementData,newCapacity);
  18. }
  19. }

The number of times this list has been structurally modified.

这是对modCount的解释,意为记录list结构被改变的次数(观察源码可以发现每次调用ensureCapacoty方法,modCount的值都将增加,但未必数组 结构会改变,所以感觉对modCount的解释不是很到位)。

增加modCount之后,判断minCapacity(即size+1)是否大于oldCapacity(即elementData.length),若大于,则调整容量为 max((oldCapacity*3)/2+1 , minCapacity ),调整elementData容量为新的容量,即将返回一个内容为原数组元素,大小为新容量的 新数组 赋给elementData;否则不做操作。

所以调用ensureCapacity至少将elementData的容量增加的1,所以elementData[size]不会出现越界的情况。

容量的拓展将导致数组元素的复制,多次拓展容量将执行多次整个数组内容的复制。若提前能大致判断list的长度,调用ensureCapacity调整容量,将有效的提高运行速度。

可以理解提前分配好空间可以提高运行速度,但是测试发现提高的并不是很大,而且若list原本数据量就不会很大效果将更不明显。

add(int index, E element)

add(int index,E element)在指定位置插入元素。

[java] view plain copy
  1. publicvoidadd(intindex,Eelement){
  2. if(index>size||index<0)
  3. thrownewIndexOutOfBoundsException("Index:"+index+",Size:"+size);
  4. ensureCapacity(size+1);//IncrementsmodCount!!
  5. System.arraycopy(elementData,index,elementData,index+1, size-index);
  6. elementData[index]=element;
  7. size++;
  8. }

      System.arraycopy
     public static void arraycopy(Objectsrc, intsrcPos,  Objectdest, intdestPos,  intlength)
 
src - 源数组。 
srcPos - 源数组中的起始位置。 
dest - 目标数组。 
destPos - 目标数据中的起始位置。 
length - 要复制的数组元素的数量。 
 

首先判断指定位置index是否超出elementData的界限,之后调用ensureCapacity调整容量(若容量足够则不会拓展),调用System.arraycopy将elementData从index开始的size-index个元素复制到index+1至size+1的位置(即index开始的元素都向后移动一个位置),然后将index位置的值指向element。

addAll(Collection<? extends E> c)

[java] view plain copy
  1. publicbooleanaddAll(Collection<?extendsE>c){
  2. Object[]a=c.toArray();
  3. intnumNew=a.length;
  4. ensureCapacity(size+numNew);//IncrementsmodCount
  5. System.arraycopy(a,0,elementData,size,numNew);
  6. size+=numNew;
  7. returnnumNew!=0;
  8. }

先将集合c转换成数组,根据转换后数组的程度和ArrayList的size拓展容量,之后调用System.arraycopy方法复制元素到elementData的尾部,调整size。根据返回的内容分析,只要集合c的大小不为空,即转换后的数组长度不为0则返回true。

addAll(int index,Collection<? extends E> c)

[java] view plain copy
  1. publicbooleanaddAll(intindex,Collection<?extendsE>c){
  2. if(index>size||index<0)
  3. thrownewIndexOutOfBoundsException("Index:"+index+",Size:"+size);
  4. Object[]a=c.toArray();
  5. intnumNew=a.length;
  6. ensureCapacity(size+numNew);//IncrementsmodCount
  7. intnumMoved=size-index;
  8. if(numMoved>0)
  9. System.arraycopy(elementData,index,elementData,index+numNew,numMoved);
  10. System.arraycopy(a,0,elementData,index,numNew);
  11. size+=numNew;
  12. returnnumNew!=0;
  13. }

先判断index是否越界。其他内容与addAll(Collection<? extends E> c)基本一致,只是复制的时候先将index开始的元素向后移动X

(c转为数组后的长度)个位置(也是一个复制的过程),之后将数组内容复制到elementData的index位置至index+X。

clear()

[java] view plain copy
  1. publicvoidclear(){
  2. modCount++;
  3. //Letgcdoitswork
  4. for(inti=0;i<size;i++)
  5. elementData[i]=null;
  6. size=0;
  7. }

clear的时候并没有修改elementData的长度(好不容易申请、拓展来的,凭什么释放,留着搞不好还有用呢。这使得确定不再修改list内容之后最好调用trimToSize来释放掉一些空间),只是将所有元素置为null,size设置为0。

clone()

返回此 ArrayList 实例的浅表副本。(不复制这些元素本身。)

[java] view plain copy
  1. publicObjectclone(){
  2. try{
  3. ArrayList<E>v=(ArrayList<E>)super.clone();
  4. v.elementData=Arrays.copyOf(elementData,size);
  5. v.modCount=0;
  6. returnv;
  7. }catch(CloneNotSupportedExceptione){
  8. //thisshouldn'thappen,sinceweareCloneable
  9. thrownewInternalError();
  10. }
  11. }

调用父类的clone方法返回一个对象的副本,将返回对象的elementData数组的内容赋值为原对象elementData数组的内容,将副本的modCount设置为0。

contains(Object)

[html] view plain copy
  1. publicbooleancontains(Objecto){
  2. returnindexOf(o)>=0;
  3. }

indexOf方法返回值与0比较来判断对象是否在list中。接着看indexOf。

indexOf(Object)

[java] view plain copy
  1. publicintindexOf(Objecto){
  2. if(o==null){
  3. for(inti=0;i<size;i++)
  4. if(elementData[i]==null)
  5. returni;
  6. }else{
  7. for(inti=0;i<size;i++)
  8. if(o.equals(elementData[i]))
  9. returni;
  10. }
  11. return-1;
  12. }

通过遍历elementData数组来判断对象是否在list中,若存在,返回index([0,size-1]),若不存在则返回-1。所以contains方法可以通过indexOf(Object)方法的返回值来判断对象是否被包含在list中。

既然看了indexOf(Object)方法,接着就看lastIndexOf,光看名字应该就明白了返回的是传入对象在elementData数组中最后出现的index值。

[java] view plain copy
  1. publicintlastIndexOf(Objecto){
  2. if(o==null){
  3. for(inti=size-1;i>=0;i--)
  4. if(elementData[i]==null)
  5. returni;
  6. }else{
  7. for(inti=size-1;i>=0;i--)
  8. if(o.equals(elementData[i]))
  9. returni;
  10. }
  11. return-1;
  12. }

采用了从后向前遍历element数组,若遇到Object则返回index值,若没有遇到,返回-1。

get(int index)

这个方法看着很简单,应该是返回elementData[index]就完了。

[java] view plain copy
  1. publicEget(intindex){
  2. RangeCheck(index);
  3. return(E)elementData[index];
  4. }

但看代码的时候看到调用了RangeCheck方法,而且还是大写的方法,看看究竟有什么内容吧。

[java] view plain copy
  1. /**
  2. *Checksifthegivenindexisinrange.
  3. */
  4. privatevoidRangeCheck(intindex){
  5. if(index>=size)
  6. thrownewIndexOutOfBoundsException("Index:"+index+",Size:"+size);
  7. }

就是检查一下是不是超出数组界限了,超出了就抛出IndexOutBoundsException异常。为什么要大写呢???

isEmpty()

public boolean isEmpty() { return size == 0; }

直接返回size是否等于0。

remove(int index)

[java] view plain copy
  1. publicEremove(intindex){
  2. RangeCheck(index);
  3. modCount++;
  4. EoldValue=(E)elementData[index];
  5. intnumMoved=size-index-1;
  6. if(numMoved>0)
  7. System.arraycopy(elementData,index+1,elementData,index,numMoved);
  8. elementData[--size]=null;//Letgcdoitswork
  9. returnoldValue;
  10. }

首先是检查范围,修改modCount,保留将要被移除的元素,将移除位置之后的元素向前挪动一个位置,将list末尾元素置空(null),返回被移除的元素。

remove(Object o)

[java] view plain copy
  1. publicbooleanremove(Objecto){
  2. if(o==null){
  3. for(intindex=0;index<size;index++)
  4. if(elementData[index]==null){
  5. fastRemove(index);
  6. returntrue;
  7. }
  8. }else{
  9. for(intindex=0;index<size;index++)
  10. if(o.equals(elementData[index])){
  11. fastRemove(index);
  12. returntrue;
  13. }
  14. }
  15. returnfalse;
  16. }
首先通过代码可以看到,当移除成功后返回true,否则返回false。 remove(Object o)中通过遍历element寻找是否存在传入对象,一旦找到就调用fastRemove移除对象。

为什么找到了元素就知道了index,不通过remove(index)来移除元素呢?因为fastRemove跳过了判断边界的处理,因为找到元素就相当于确定了index不会超过边界,而且fastRemove并不返回被移除的元素。

下面是fastRemove的代码,基本和remove(index)一致。

[java] view plain copy
  1. privatevoidfastRemove(intindex){
  2. modCount++;
  3. intnumMoved=size-index-1;
  4. if(numMoved>0)
  5. System.arraycopy(elementData,index+1,elementData,index,
  6. numMoved);
  7. elementData[--size]=null;//Letgcdoitswork
  8. }

removeRange(int fromIndex,int toIndex) 从列表中移除索引在fromIndex(包括)和toIndex(不包括)之间的所有元素。

[java] view plain copy
  1. protectedvoidremoveRange(intfromIndex,inttoIndex){
  2. modCount++;
  3. intnumMoved=size-toIndex;
  4. System.arraycopy(elementData,toIndex,elementData,fromIndex,numMoved);
  5. //Letgcdoitswork
  6. intnewSize=size-(toIndex-fromIndex);
  7. while(size!=newSize)
  8. elementData[--size]=null;
  9. }

执行过程是将elementData从toIndex位置开始的元素向前移动到fromIndex,然后将toIndex位置之后的元素全部置空顺便修改size

这个方法是protected,及受保护的方法,为什么这个方法被定义为protected呢?

这是一个解释,但是可能不容易看明白。http://stackoverflow.com/questions/2289183/why-is-javas-abstractlists-removerange-method-protected

先看下面这个例子

[java] view plain copy
  1. ArrayList<Integer>ints=newArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6));
  2. //fromIndexlowendpoint(inclusive)ofthesubList
  3. //toIndexhighendpoint(exclusive)ofthesubList
  4. ints.subList(2,4).clear();
  5. System.out.println(ints);
输出结果是[0, 1, 4, 5, 6],结果是不是像调用了removeRange(int fromIndex,int toIndex)!哈哈哈,就是这样的。

但是为什么效果相同呢?是不是调用了removeRange(int fromIndex,int toIndex)呢?

(参考文章:使用java.util.List.subList时最好小心点http://www.cnblogs.com/gaojing/archive/2012/06/17/java-list-sublist-caution.html)

java.util.List中有一个subList方法,用来返回一个list的一部分的视图。

List<E> subList(int fromIndex, int toIndex);

它返回原来list的从[fromIndex, toIndex)之间这一部分的视图,之所以说是视图,是因为实际上,返回的list是靠原来的list支持的。

所以,你对原来的list和返回的list做的“非结构性修改”(non-structural changes),都会影响到彼此对方。

所谓的“非结构性修改”,是指不涉及到list的大小改变的修改。相反,结构性修改,指改变了list大小的修改。

那么,如果涉及到结构性修改会怎么样呢?

如果发生结构性修改的是返回的子list,那么原来的list的大小也会发生变化

而如果发生结构性修改的是原来的list(不包括由于返回的子list导致的改变),那么返回的子list语义上将会是undefined。

在AbstractList(ArrayList的父类)中,undefined的具体表现形式是抛出一个ConcurrentModificationException。

因此,如果你在调用了sublist返回了子list之后,如果修改了原list的大小,那么之前产生的子list将会失效,变得不可使用。

tips:如何删除一个list的某个区段,比如删除list的第2-5个元素?

方法是: 可以利用sublist的幕后还是原来的list的这个特性,比如

list.subList(from, to).clear();   这样就可以了。

示例代码:

public static void main(String[] args) {
        for(int i = 0; i < 5; i++){
      parentList.add(String.valueOf(i)); // 0 ,1 ,2, 3 ,4
    }
   
    List<String> subList = parentList.subList(1, 3);
    for(String s : subList){
      System.out.println(s);// 1 , 2
    }
   
    //non-structural modification by sublist, reflect parentList
    subList.set(0, "new 1"); //new 1 , 2
    for(String s : parentList){
      System.out.println(s);//0, new 1, 2, 3, 4
    }
   
    //structural modification by sublist, reflect parentList
    subList.add(String.valueOf(2.5)); //new 1 , 2 , 2.5
    for(String s : parentList){
      System.out.println(s);// 0, new 1, 2, 2.5, 3,  4
    }
   
    //non-structural modification by parentList, reflect sublist
    parentList.set(2, "new 2");// 0, new 1, new 2, 2.5, 3,  4
    for(String s : subList){
      System.out.println(s);// new 1, new 2
    }
   
    //structural modification by parentList, sublist becomes undefined(throw exception)
    parentList.add("undefine");
    for(String s : subList){
      System.out.println(s);
    }
    subList.get(0); //java.util.ConcurrentModificationException


set(int index,E element)

[java] view plain copy
  1. publicEset(intindex,Eelement){
  2. RangeCheck(index);
  3. EoldValue=(E)elementData[index];
  4. elementData[index]=element;
  5. returnoldValue;
  6. }

首先检查范围,用新元素替换旧元素并返回旧元素。

size()

size()方法直接返回size。


toArray() 返回包含此列表中所有元素的数组。

[java] view plain copy
  1. publicObject[]toArray(){
  2. returnArrays.copyOf(elementData,size);
  3. }

调用Arrays.copyOf将返回一个数组,数组内容是size个elementData的元素,即拷贝elementData从0至size-1位置的元素到新数组并返回。


toArray(T[] a)

[java] view plain copy
  1. public<T>T[]toArray(T[]a){
  2. if(a.length<size)
  3. //Makeanewarrayofa'sruntimetype,butmycontents:
  4. return(T[])Arrays.copyOf(elementData,size,a.getClass());
  5. System.arraycopy(elementData,0,a,0,size);
  6. if(a.length>size)
  7. a[size]=null;
  8. returna;
  9. }

如果传入数组的长度小于size,返回一个新的数组,大小为size,类型与传入数组相同。

所传入数组长度与size相等,则将elementData复制到传入数组中并返回传入的数组。

若传入数组长度大于size,除了复制elementData外,还将把返回数组的第size个元素置为空

trimToSize()

[java] view plain copy
  1. publicvoidtrimToSize(){
  2. modCount++;
  3. intoldCapacity=elementData.length;
  4. if(size<oldCapacity){
  5. elementData=Arrays.copyOf(elementData,size);
  6. }
  7. }

由于elementData的长度会被拓展size标记的是其中包含的元素的个数

所以会出现size很小但elementData.length很大的情况,将出现空间的浪费。

trimToSize将返回一个新的数组给elementData,元素内容保持不变,length与size相同,节省空间。

学习Java最好的方式还必须是读源码。读完源码你才会发现这东西为什么是这么玩的,有哪些限制,关键点在哪里等等。而且这些源码都是大牛们写的,你能从中学习到很多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值