JAVA ArrayList details (sample) _java

Source: Internet
Author: User
Tags addall int size object object serialization

The 1th part ArrayList introduction
ArrayList is an array queue, which is the equivalent of a dynamic array. Its capacity can grow dynamically compared to an array in Java. It inherits from Abstractlist, implements the list, randomaccess, cloneable, java.io.Serializable these interfaces.
ArrayList inherited the Abstractlist and realized the list. It is an array queue that provides related additions, deletions, modifications, and traversal functions.
ArrayList implements the Randmoaccess interface, which provides a random access function. Randmoaccess is a list implemented in Java to provide quick access to the list. In ArrayList, we can quickly get the element object by the ordinal of the element, which is the fast random access. Later, we'll compare the efficiency of the list's "Quick Random access" and "access via iterator iterator."
ArrayList implements the Cloneable interface, which covers the function clone () and can be cloned.
ArrayList implements the Java.io.Serializable interface, which means that ArrayList supports serialization and can be transmitted through serialization.
Unlike vectors, operations in ArrayList are not thread-safe. Therefore, it is recommended that ArrayList be used in a single thread, while vectors or copyonwritearraylist can be selected in multiple threads.

The inheritance relationship of ArrayList

The relationship between ArrayList and collection is as follows:

ArrayList constructors

Copy Code code as follows:

Default constructor
ArrayList ()
Capacity is the default capacity size for ArrayList. When the capacity is insufficient due to increased data, the capacity adds half of the last capacity size.
ArrayList (int capacity)
Create a ArrayList that contains collection
ArrayList (collection< extends e> Collection)






API for ArrayList


Copy Code code as follows:



APIs defined in the collection


Boolean Add (E object)


Boolean AddAll (collection&lt;? extends e&gt; Collection)


void Clear ()


Boolean contains (Object object)


Boolean Containsall (collection&lt;?&gt; Collection)


Boolean equals (Object object)


int Hashcode ()


Boolean IsEmpty ()


Iterator&lt;e&gt; iterator ()


Boolean Remove (Object)


Boolean RemoveAll (collection&lt;?&gt; Collection)


Boolean Retainall (collection&lt;?&gt; Collection)


int size ()


&lt;T&gt; t[] ToArray (t[] array)


Object[] ToArray ()


APIs defined in the Abstractcollection


void Add (int location, E object)


Boolean addall (int location, collection&lt;? extends e&gt; Collection)


E get (int location)


int IndexOf (Object object)


int LastIndexOf (Object object)


listiterator&lt;e&gt; listiterator (int location)


Listiterator&lt;e&gt; Listiterator ()


E Remove (int location)


e Set (int location, E object)


list&lt;e&gt; sublist (int start, int end)


ArrayList the new API


Object Clone ()


void ensurecapacity (int minimumcapacity)


void TrimToSize ()


void RemoveRange (int fromindex, int toindex)











2nd part ArrayList source analysis
To get a better idea of the ArrayList principle, the following is an analysis of the ArrayList source code. ArrayList is implemented through arrays, the source code is relatively easy to understand.


Copy Code code as follows:



Package java.util;


public class Arraylist&lt;e&gt; extends abstractlist&lt;e&gt;


Implements List&lt;e&gt, Randomaccess, cloneable, java.io.Serializable


{


Serial version number


Private static final long serialversionuid = 8683452581122892189L;


To save an array of data in ArrayList


Private transient object[] elementdata;


Number of actual data in ArrayList


private int size;


ArrayList a constructor with capacity size.


Public ArrayList (int initialcapacity) {


Super ();


if (initialcapacity &lt; 0)


throw new IllegalArgumentException ("illegal Capacity:" +


initialcapacity);


Create a new array


This.elementdata = new Object[initialcapacity];


}


The ArrayList constructor. The default capacity is 10.


Public ArrayList () {


This (10);


}


Create a ArrayList that contains collection


Public ArrayList (collection&lt;? extends e&gt; c) {


Elementdata = C.toarray ();


size = Elementdata.length;


C.toarray might (incorrectly) not return object[] (6260652)


if (Elementdata.getclass ()!= object[].class)


Elementdata = arrays.copyof (elementdata, size, object[].class);


}

Set current capacity value to = number of actual elements
public void TrimToSize () {
modcount++;
int oldcapacity = Elementdata.length;
if (Size < oldcapacity) {
Elementdata = arrays.copyof (elementdata, size);
}
}

Determine the capacity of the arrarlist.


If the ArrayList capacity is insufficient to accommodate all current elements, set the new capacity = "(Original capacity x3)/2 + 1"


public void ensurecapacity (int mincapacity) {


To "Modify statistics" +1


modcount++;


int oldcapacity = Elementdata.length;


If the current capacity is insufficient to accommodate the current number of elements, set the new capacity = "(Original capacity x3)/2 + 1"


if (Mincapacity &gt; Oldcapacity) {


Object olddata[] = elementdata;


int newcapacity = (oldcapacity * 3)/2 + 1;


if (Newcapacity &lt; mincapacity)


newcapacity = mincapacity;


Elementdata = arrays.copyof (Elementdata, newcapacity);


}


}


add Element E


Public boolean Add (E e) {


Determine the capacity size of the ArrayList


Ensurecapacity (size + 1); Increments modcount!!


Add E to ArrayList


elementdata[size++] = e;


return true;


}


Returns the actual size of the ArrayList


public int size () {


return size;


}


Returns whether ArrayList contains object (o)


Public Boolean contains (Object o) {


return IndexOf (O) &gt;= 0;


}


Returns whether the ArrayList is empty


public Boolean IsEmpty () {


return size = = 0;


}


Forward lookup, returns the index value of the element


public int indexOf (Object o) {


if (o = = null) {


for (int i = 0; i &lt; size; i++)


if (elementdata[i]==null)


return i;


} else {


for (int i = 0; i &lt; size; i++)


if (O.equals (Elementdata[i]))


return i;


}


return-1;


}


Reverse lookup, returning the index value of an element


public int LastIndexOf (Object o) {


if (o = = null) {


for (int i = size-1 i &gt;= 0; i--)


if (elementdata[i]==null)


return i;


} else {


for (int i = size-1 i &gt;= 0; i--)


if (O.equals (Elementdata[i]))


return i;


}


return-1;


}


Reverse lookup (lookup from end of array), return index value of Element (O)


public int LastIndexOf (Object o) {


if (o = = null) {


for (int i = size-1 i &gt;= 0; i--)


if (elementdata[i]==null)


return i;


} else {


for (int i = size-1 i &gt;= 0; i--)


if (O.equals (Elementdata[i]))


return i;


}


return-1;


}





Returns an object array of ArrayList


Public object[] ToArray () {


Return arrays.copyof (elementdata, size);


}


Returns an array of ArrayList templates. The so-called template array, that is, you can set the T to any data type


Public &lt;T&gt; t[] ToArray (t[] a) {


If the size of the array a &lt; The number of ArrayList elements;


Creates a new t[] array, the array size is the number of ArrayList elements, and copies "ArrayList" to the new array


if (A.length &lt; size)


Return (t[]) arrays.copyof (elementdata, size, A.getclass ());


If the size of the array a &gt;= the number of ArrayList elements;


All elements of ArrayList are copied to array a.


System.arraycopy (elementdata, 0, a, 0, size);


if (A.length &gt; Size)


A[size] = null;


return A;


}


Gets the element value of the index position


Public E get (int index) {


Rangecheck (index);


Return (E) Elementdata[index];


}


Set the value of index position to element


Public E Set (int index, E element) {


Rangecheck (index);


E OldValue = (e) elementdata[index];


Elementdata[index] = element;


return oldValue;


}


Add E to ArrayList


Public boolean Add (E e) {


Ensurecapacity (size + 1); Increments modcount!!


elementdata[size++] = e;


return true;


}


Add e to the specified location of the ArrayList


public void Add (int index, E element) {


if (Index &gt; Size | | Index &lt; 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++;


}


Delete ArrayList the element at the specified location


Public E-Remove (int index) {


Rangecheck (index);


modcount++;


E OldValue = (e) elementdata[index];


int nummoved = size-index-1;


if (nummoved &gt; 0)


System.arraycopy (Elementdata, index+1, Elementdata, Index,


nummoved);


Elementdata[--size] = null; Let GC does its work


return oldValue;


}


Deletes the specified element of the ArrayList


public boolean remove (Object o) {


if (o = = null) {


for (int index = 0; index &lt; size; index++)


if (elementdata[index] = = null) {


Fastremove (index);


return true;


}


} else {


for (int index = 0; index &lt; size; index++)


if (O.equals (Elementdata[index])) {


Fastremove (index);


return true;


}


}


return false;


}

Quickly delete index elements


private void Fastremove (int index) {


modcount++;


int nummoved = size-index-1;


Starting with "index+1", replace the preceding element with the following elements.


if (nummoved &gt; 0)


System.arraycopy (Elementdata, index+1, Elementdata, Index,


nummoved);


Set the last element to null


Elementdata[--size] = null; Let GC does its work


}


Delete Element


public boolean remove (Object o) {


if (o = = null) {


for (int index = 0; index &lt; size; index++)


if (elementdata[index] = = null) {


Fastremove (index);


return true;


}


} else {


Facilitates ArrayList, finds "element O", deletes, and returns True.


for (int index = 0; index &lt; size; index++)


if (O.equals (Elementdata[index])) {


Fastremove (index);


return true;


}


}


return false;


}


Empty ArrayList, set all elements to null


public void Clear () {


modcount++;


for (int i = 0; i &lt; size; i++)


Elementdata[i] = null;


size = 0;


}


Append the collection C to the ArrayList


public boolean addall (collection&lt;? extends e&gt; c) {


Object[] A = C.toarray ();


int numnew = A.length;


Ensurecapacity (size + numnew); Increments Modcount


System.arraycopy (A, 0, elementdata, size, numnew);


Size + = Numnew;


return numnew!= 0;


}


Add collection C to ArrayList starting at the index position


public boolean addall (int index, COLLECTION&LT;? extends e&gt; c) {


if (Index &gt; Size | | Index &lt; 0)


throw New Indexoutofboundsexception (


"Index:" + index + ", size:" + size);


Object[] A = C.toarray ();


int numnew = A.length;


Ensurecapacity (size + numnew); Increments Modcount


int nummoved = Size-index;


if (nummoved &gt; 0)


System.arraycopy (Elementdata, index, elementdata, index + numnew,


nummoved);


System.arraycopy (A, 0, Elementdata, index, numnew);


Size + = Numnew;


return numnew!= 0;


}


Deletes all elements between Fromindex and Toindex.


protected void RemoveRange (int fromindex, int toindex) {


modcount++;


int nummoved = Size-toindex;


System.arraycopy (Elementdata, Toindex, Elementdata, Fromindex,


nummoved);


Let GC does its work


int newsize = size-(TOINDEX-FROMINDEX);


while (size!= newsize)


Elementdata[--size] = null;


}


private void Rangecheck (int index) {


if (index &gt;= size)


throw New Indexoutofboundsexception (


"Index:" +index+ ", Size:" +size);


}

Cloning functions


Public Object Clone () {


try {


Arraylist&lt;e&gt; v = (arraylist&lt;e&gt;) super.clone ();


Copies all elements of the current ArrayList into V


V.elementdata = arrays.copyof (elementdata, size);


V.modcount = 0;


return v;


catch (Clonenotsupportedexception e) {


This shouldn ' t happen, since we are cloneable


throw new Internalerror ();


}


}

Write function for java.io.Serializable


Writes the ArrayList "capacity, all element values" to the output stream


private void WriteObject (Java.io.ObjectOutputStream s)


Throws java.io.ioexception{


Write out element count, and any hidden stuff


int expectedmodcount = Modcount;


S.defaultwriteobject ();


Write "Capacity of the array"


S.writeint (elementdata.length);


Write "Every element of an array"


for (int i=0; i&lt;size; i++)


S.writeobject (Elementdata[i]);


if (Modcount!= expectedmodcount) {


throw new Concurrentmodificationexception ();


}


}

Java.io.Serializable read function: read from Write mode
Read the ArrayList "capacity" first, then read the "All element values"
private void ReadObject (Java.io.ObjectInputStream s)
Throws Java.io.IOException, ClassNotFoundException {
Read in size, and any hidden stuff
S.defaultreadobject ();
Read the ArrayList "capacity" from the input stream
int arraylength = S.readint ();
Object[] A = Elementdata = new Object[arraylength];
Read "All element values" from the input stream
for (int i=0; i<size; i++)
A[i] = S.readobject ();
}
}




Summarize:


ArrayList actually saves data through an array. When we construct ArrayList, if we use the default constructor, the default capacity size of ArrayList is 10.


(02) When the ArrayList capacity is insufficient to accommodate all elements, ArrayList will reset the capacity: the New capacity = "(Original capacity x3)/2 + 1".


(ArrayList) a cloned function that clones all elements into an array.


(ArrayList) the way to implement Java.io.Serializable. When written to the output stream, writes "capacity" and then writes "Each element", reads "capacity" and then reads "Each element" when the input stream is read out.








3rd part ArrayList traversal mode
ArrayList supports 3 ways to traverse


(01) The first kind, through the iterator traversal. That is, through the iterator to traverse.


Copy Code code as follows:

Integer value = null;
Iterator iter = List.iterator ();
while (Iter.hasnext ()) {
Value = (Integer) iter.next ();
}



(02) The second, random access, through the index value to traverse.


Because ArrayList implements the Randomaccess interface, it supports random access to elements via index values.


Copy Code code as follows:

Integer value = null;
int size = List.size ();
for (int i=0; i<size; i++) {
Value = (Integer) list.get (i);
}



(03) The third type, for loop traversal. As follows:


Copy Code code as follows:

Integer value = null;
for (Integer integ:list) {
value = Integ;
}



Below is an example that compares the efficiency of these 3 ways, with instance code (ARRAYLISTRANDOMACCESSTEST.JAVA) as follows:


Copy Code code as follows:



Import java.util.*;


Import java.util.concurrent.*;


/*


* @desc ArrayList traversal method and efficiency of the test program.


*


* @author Skywang


*/


public class Arraylistrandomaccesstest {


public static void Main (string[] args) {


List List = new ArrayList ();


for (int i=0; i&lt;100000; i++)


List.add (i);


israndomaccesssupported (list);


Iteratorthroughrandomaccess (list);


Iteratorthroughiterator (list);


IteratorThroughFor2 (list);





}


private static void israndomaccesssupported (List list) {


if (list instanceof randomaccess) {


System.out.println ("Randomaccess implemented!");


} else {


System.out.println ("Randomaccess not implemented!");


}


}


public static void Iteratorthroughrandomaccess (List list) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


for (int i=0; i&lt;list.size (); i++) {


List.get (i);


}


Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("iteratorthroughrandomaccess:" + interval+ "MS");


}


public static void Iteratorthroughiterator (List list) {


Long StartTime;


Long Endtime;


StartTime = System.currenttimemillis ();


for (Iterator iter = List.iterator (); Iter.hasnext ();) {


Iter.next ();


}


Endtime = System.currenttimemillis ();


Long interval = Endtime-starttime;


System.out.println ("Iteratorthroughiterator:" + interval+ "MS");


}

public static void IteratorThroughFor2 (List list) {
Long StartTime;
Long Endtime;
StartTime = System.currenttimemillis ();
for (Object obj:list)

Endtime = System.currenttimemillis ();
Long interval = Endtime-starttime;
System.out.println ("IteratorThroughFor2:" + interval+ "MS");
}
}




Run Result:


Iteratorthroughrandomaccess:3 ms


Iteratorthroughiterator:8 ms


Iteratorthroughfor2:5 ms


Thus, when traversing ArrayList, the use of random access (that is, through the index number access) is the most efficient, and the efficiency of the use of iterators is the lowest!








Part 4th ToArray () exception
When we call the ToArray () in ArrayList, we may have encountered an exception that throws a "java.lang.ClassCastException". Let's talk about what's going on here.


The ArrayList provides 2 toarray () functions:


Object[] ToArray ()


&lt;T&gt; t[] ToArray (t[] contents)


Calling the ToArray () function throws a "java.lang.ClassCastException" exception, but the call to ToArray (t[] contents) returns normal t[].


ToArray () throws an exception because ToArray () returns a object[] array, converting object[to another type (for example, object[to integer[]) throws " Java.lang.ClassCastException "Exception, because Java does not support downward transition. The details can refer to the ToArray () of the source Introduction section of the previous Arraylist.java.


The solution to this problem is to invoke &lt;T&gt; t[] ToArray (t[] contents), rather than object[] ToArray ().


Calls to ToArray (t[] contents) Return t[can be implemented in several ways.


Copy Code code as follows:

ToArray (t[] contents) Call Way A
public static integer[] VectorToArray1 (arraylist<integer> v) {
integer[] NewText = new integer[v.size ()];
V.toarray (NewText);
return newtext;
}
ToArray (t[] contents) invocation mode two. Most commonly used!
public static integer[] VectorToArray2 (arraylist<integer> v) {
Integer[] NewText = (integer[]) V.toarray (new integer[0));
return newtext;
}
ToArray (t[] contents) Invocation mode three
public static integer[] VectorToArray3 (arraylist<integer> v) {
integer[] NewText = new integer[v.size ()];
Integer[] Newstrings = (integer[]) V.toarray (NewText);
return newstrings;
}









Part 5th ArrayList example
This article introduces the common API of ArrayList through an example (Arraylisttest.java).


Copy Code code as follows:



Import java.util.*;


/*


* @desc ArrayList common API test procedures


* @author Skywang


* @email kuiwu-wang@163.com


*/


public class Arraylisttest {


public static void Main (string[] args) {





Create ArrayList


ArrayList list = new ArrayList ();


The ""


List.add ("1");


List.add ("2");


List.add ("3");


List.add ("4");


Add the following element to position 1th


List.add (0, "5");


Get 1th Element


System.out.println ("The" "The" is: "+ list.get (0));


Delete "3"


List.remove ("3");


Get the size of the ArrayList


System.out.println ("Arraylist size=:" + list.size ());


Determine if "3" is included in the list


System.out.println ("ArrayList contains 3 is:" + list.contains (3));


Set the 2nd element to 10


List.set (1, "10");


Traversing ArrayList via iterator


for (Iterator iter = List.iterator (); Iter.hasnext ();) {


System.out.println ("Next is:" + iter.next ());


}


Convert ArrayList to an array


String[] arr = (string[]) List.toarray (new string[0));


for (String Str:arr)


System.out.println ("str:" + str);


Empty ArrayList


List.clear ();


To determine whether ArrayList is empty


System.out.println ("ArrayList is empty:" + list.isempty ());


}


}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.