ARRAYLIST source code analysis

xiaoxiao2021-03-06  53

Finally, the first specific class can be started. We should be very familiar to ArrayList, whether you understand how it is implemented, but we are all used everywhere. The declaration is as follows:

Public Class Arraylist Extends AbstractList Implements List, Randomaccess, Cloneable, Java.io.Serializable

About ABSTRACTLIST: http: //blog.9cbs.net/treeroot/archive/2004/09/14/104743.aspx About list: http://blog.9cbs.net/treeroot/archive/2004/09/14/104638 .aspx about randomaccess: http://blog.9cbs.net/treeroot/archive/2004/09/14/104538.aspx about cloneable: http://blog.9cbs.net/treeroot/archive/2004/09/07 /96936.aspx About java.io.Serializeable: Mainly used for object serialization.

Private statino = 8683452581122892189L; version control

Private Transient Object ElementData []; internal structure, it is an array where it is not allowed to serialize.

Private int size; the size of this list is the number of elements.

public ArrayList (int initialCapacity) {super (); if (initialCapacity <0) throw new IllegalArgumentException ( "Illegal Capacity:" initialCapacity); this.elementData = new Object [initialCapacity];} constructor initializes the internal size of the array is designated Note that the list is empty.

Public arraylist () {this (10);} The default initial internal array size is 10, why is 10 if there is no reason, it may be appropriate.

Public ArrayList (Collection C) {size = c.size (); // allow 10% room for growth elementdata = new object [(int) Math.min ((size * 110L) /100, integer.max_value)]; c .Toarray (ElementData);} Initially, the ArrayList is initiated by a collection, and the internal array application is larger, mainly for increasing efficiency. Note that the C.Toarray (ElementData) method is called, which will not generate a new array here, if using ElementData = C.Toarray () efficiency is much more efficient. Also, the static method Min of Math is called to obtain a smaller value.

public void trimToSize () {modCount ; int oldCapacity = elementData.length; if (size oldCapacity) {Object oldData [] = elementData; int newCapacity = (oldCapacity * 3) / 2 1; if (newCapacity

Public int size () {return size;} Return to the size

Public Boolean iSempty () {return size == 0;

Public Boolean Contains (Object ELEM) {Return INDEXOF (ELEM)> = 0;} Whether to include the specified element, the indexof () method is called.

Public int indexof (Object elem) {if (ELEM == NULL) {for (int i = 0; i = 0; I -) IF (ELEMENTDATA [I] == Null) Return I;} else {for (int i = size-1 i> = 0; I - ELEM.EQUALS (ElementData [i])) RETURN I;} return -1;} This method is the same as the above, the order is different.

Public Object Clone () {Try {ArrayList V = (arraylist) super.clone (); v.elementdata = new object [size]; system.Arraycopy (ElementData, 0, v.elementdata, 0, size); v.modcount = 0; Return V;} catch (clonenotsupportedException e) {// this kind ofn't happen, Since We arecloneable throw new interface, the client () method overrides the client () method in Object, Realizing Clone, Note that this is a shallow Copy, the elements in the arrays in the two ArrayList are the same because system.ArrayCopy is a shallow copy.

Public object [] toservation () {object [] result = new object [size]; system.Arraycopy (ElementData, 0, Result, 0, size); Return Result;} Returns an array of ArrayList elements, note that although it is generated A new array, but the elements in array elements and collections are shared. In the Collection interface, this is safe, and the example below demonstrates this effect. EG1: arraylist al = new arraylist (); al. ADD ("Hello"); object [] a = al.toArray (); stringbuffer sb = (stringbuffer) a [0]; sb.append (" "); // Change the array element also changed the elements in the original ArrayList system.out.println (Al.Get (0)); here do not use String to replace StringBuffer because String is constant.

Public object [] toarray (object a []) {if (a.length size) a [size] = null; returnon A;} This method may not need to generate a new array, notice if array A The capacity is too large, only set to NULL at SIZE. Public Object GET (INDEX); Return ElementData [Index];

Public Object Set (INDEX, Object Element) {RangeCheck (Index); Object OldValue = ElementData [Index]; ElementData [index] = element; returna} Update the value of the specified location and access the original value.

Public Boolean Add (Object O) {ENSURECAPACITY (SIZE 1); // Incremen Modcount !! ElementData [Size ] = O; Return True;} Add a new element to the end, the previous new method must call ENSURECAPACITY Method, the ADD (SIZE, O) method is not called here.

Public void add (int index, object element) {if (index> size || index <0) Throw new indexoutofboundsexception ("INDEX:" index ", size:" size); EnsureCapacity (Size 1); // Increments Modcount !! System.Arraycopy (ElementData, Index, ElementData, Index 1, Size - Index); ElementData [index] = Element; Size ;} Insert an element in the specified location, specify the element and the elements behind.

public Object remove (int index) {RangeCheck (index); modCount ; Object oldValue = elementData [index]; int numMoved = size - index - 1; if (numMoved> 0) System.arraycopy (elementData, index 1, elementData, Index, Nummoved; ElementData [- size] = null; // let gc do its Work Return OldValue;} Delete elements of the specified location, forward, return, return the deleted element, ElementData you should pay attention to [- -size] = NULL This statement, if not, it is possible to cause memory disclosure, because the object is actually useless, but there is another reference, if it is not set to null, GC will not recover this space. More accumulation, it is possible to cause memory disclosure, here is only possible, not necessarily. Public void clear () {modcount ; // let gc do its Work for (int i = 0; i

Public Boolean Addall (Collection C) {Modcount ; Int NumNew = C.Size (); ENSURECAPACITY (SIZE NUMNEW); Iterator E = C.Iterator (); for (int i = 0; i

ElementData [SIZE ] = E.next ();

Return NumNew! = 0;

}

Add the elements in the collection C to the end of ArrayList, add success to return True, if the set C is empty, return false.

Public Boolean Addall (INDEX> SIZE || Index <0) throw new indexoutofboundsexception ("INDEX:" INDEX ", SIZE:" size); int NumNew = C.Size (); ensureCapacity (size numNew); // Increments modCount !! int numMoved = size - index; if (numMoved> 0) System.arraycopy (elementData, index, elementData, index numNew, numMoved); Iterator e = c.iterator ( ); For (int i = 0; i

ElementData [INDEX ] = E.next ();

Size = NumNew;

Return NumNew! = 0;

}

All elements in the specified location insertion set, and one of the above methods are substantially different, the specified position element and the later are backward.

protected void removeRange (int fromIndex, int toIndex) {modCount ; int numMoved = size - toIndex; System.arraycopy (elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newSize = size - (toIndex- FromIndex; while (size! = newsize) ElementData [- size] = null;} This is a protection method that deletes the element of the specified location fromNDEX to TOINDEX, including the front, not included. Private Void Rangecheck (int index) {if (index> = size || index <0) throw new indexoutofboundsexception ("INDEX:" INDEX ", SIZE:" size);} Do not explain.

private synchronized void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException {// Write out element count, and any hidden stuff s.defaultWriteObject (); // Write out array length s.writeInt (elementData.length) ; // Write Out All Elements in The Proper ORDER. FOR (INT i = 0; i

S.WriteObject (ElementData [i]);

}

Private synchronized void readObject (java.io.objectInputStream s) throws java.io.ioException, classnotfoundexception {

// read in size, and any hidden stuff

S.DEFAULTREADOBJECT ();

// read in Array Length And Allocate Array

Int arraylength = s.readint ();

ElementData = New Object [ArrayLength];

// read in All Elements in The Proper ORDER.

For (int i = 0; i

ElementData [I] = s.readObject ();

}

转载请注明原文地址:https://www.9cbs.com/read-116208.html

New Post(0)