Java Collection Source learning Note (ii) ArrayList analysis

Source: Internet
Author: User
Tags addall shallow copy

Java Collection Source learning Note (ii) ArrayList analysis>> about ArrayList

ArrayList directly inherits Abstractlist, realizes the list, randomaccess, cloneable, serializable interface,
Why is it called "ArrayList" because the inside of ArrayList is to store element values in an array, which is equivalent to a variable-sized array, which is a dynamic array.

(1) Inheritance and implementation
Inherits the Abstractlist, realizes the list:arraylist is an array queue, provides the related addition, the deletion, the modification, the traversal and so on function.
Implement the Randmoaccess interface: provides random access functionality. Randmoaccess is used in Java to be implemented by the list, for the list to provide quick access to the function of the ArrayList, we can quickly get the element object by the ordinal of the element, that is, fast random access.
The Cloneable interface is implemented: the function clone () is overwritten and can be cloned.
Implement the Java.io.Serializable interface: This means that the ArrayList supports serialization and can be transmitted by serialization.

(2) Thread safety
The operation in ArrayList is not thread-safe. It is recommended that you use ArrayList in a single thread, and you can select vectors or copyonwritearraylist in multiple threads.

>> Common Methods

(1) method Description
Boolean Add (E E)
Adds the specified element to the tail of this list.
void Add (int index, E Element)
Inserts the specified element into the specified position in this list.
Boolean AddAll (collection<? extends e> c)
Adds all elements in the collection to the end of this list, according to the order of elements returned by the iterator that specifies collection.
Boolean addall (int index, COLLECTION&LT;? extends e> c)
Inserts all elements from the specified collection into this list, starting at the specified location.
void Clear ()
Removes all the elements from this list.
Object Clone ()
Returns a shallow copy of this ArrayList instance.
Boolean contains (Object o)
Returns true if the specified element is contained in this list.
void ensurecapacity (int mincapacity)
If necessary, increase the capacity of this ArrayList instance to ensure that it can accommodate at least the number of elements specified by the minimum capacity parameter.
E get (int index)
Returns the element at the specified position in this list.
int indexOf (Object o)
Returns the index of the specified element that first appeared in this list, or 1 if the list does not contain elements.
Boolean IsEmpty ()
Returns true if there are no elements in this list
int lastIndexOf (Object o)
Returns the index of the specified element that occurred last in this list, or 1 if the list does not contain an index.
E Remove (int index)
Removes the element at the specified position in this list.
Boolean remove (Object o)
Removes the specified element (if any) that first appears in this list.
protected void RemoveRange (int fromIndex, int toindex)
Removes all elements in the list between FromIndex (inclusive) and Toindex (not included).
e Set (int index, e Element)
Replaces the element at the specified position in this list with the specified element.
int size ()
Returns the number of elements in this list.
Object[] ToArray ()
Returns an array containing all the elements in this list, in the appropriate order (from the first to the last element).
void TrimToSize ()
Adjusts the capacity of this ArrayList instance to the current size of the list. Applications can use this action to minimize the storage of ArrayList instances.

(2) Traversal mode
ArrayList supports 3 types of traversal methods

1. Iterate through the iterator. That is, traversing through the iterator.
2. Random access, through the index value to traverse,
ArrayList implements the Randomaccess interface, which supports random access to elements via indexed values
3.for Loop traversal

The following comparison of the efficiency of these 3 methods, the code is as follows:

public static void Main (string[] args) {arraylist<object> list=new Arraylist<> (); for (int i=0;i<10000;i++) {list.add (i);} Useiterator (list); userandomaccess (list); Useforeach (list);} public static void Useiterator (List<object> list) {Long startTime = System.currenttimemillis (); Iterator iter = List . iterator (); while (Iter.hasnext ()) {Iter.next ();}    System.out.println (System.currenttimemillis ()-starttime);}    public static void Userandomaccess (List<object> List) {Long startTime = System.currenttimemillis ();    for (int i=0; i<list.size (); i++) {list.get (i);        }system.out.println (System.currenttimemillis ()-starttime);}    public static void Useforeach (List<object> List) {Long startTime = System.currenttimemillis ();    for (Object obj:list) {; }system.out.println (System.currenttimemillis ()-starttime);} 

The output is not released, but the conclusion is that when traversing ArrayList, using random access (that is, access by index number) is the most efficient, while using iterators is relatively inefficient.

>> Source Analysis

In several commonly used collection implementation classes, the implementation code of ArrayList is the shortest, and relatively simple.
(1) Construction method
The ArrayList provides three construction methods:

Initial default size is 10

Public ArrayList () {this (10);}

The initial size of the Arrayli can be set directly

Public ArrayList (int i) {if (I < 0) {throw new IllegalArgumentException (New StringBuilder ()). Append ("Illegal capacity : "). Append (i). toString ());} else {elementdata = new Object[i];return;}}

Class with Collettion as a parameter.

Public ArrayList (Collection Collection) {elementdata = Collection.toarray (); size = Elementdata.length;if (((Object) ( Elementdata). GetClass ()! = [Ljava/lang/object;) Elementdata = arrays.copyof (elementdata, size, [Ljava/lang/object;);} ;

One is a parameterless construction method, and the other is a constructor that has a single parameter (type Collettion).

ArrayList also provides a third construction method that accepts an int value that sets the initial size of the Arrayli (the default size is 10).

(2) Data structure

Private transient Object elementdata[];p rivate int size;

ArrayList internally maintains an object array, which can be executed through the constructor ArrayList (int initialcapacity), with its initial capacity of initialcapacity, if through a constructor that does not contain arguments ArrayList () to create a ArrayList, the Elementdata capacity defaults to 10. The size of the Elementdata array grows dynamically based on the growth of the ArrayList capacity, and size is the actual size of the dynamic array.

(3) elementdata[] Why use transient retouching?
Variables defined by transient () are not serializable, but note that ArrayList also implements the Serializable interface interface, which is why?
The main purpose is to improve the efficiency of serialization.
There are 2 ways of serializing:
1. Just implement the Serializable interface.
When serializing, calls Java.io.ObjectOutputStream's Defaultwriteobject method to serialize the object.
Note: Fields that are transient decorated at this time are not serialized.
2. The serializable interface is implemented, and the WriteObject method is provided.
When serialized, the WriteObject method of the class is called. Rather than the Defaultwriteobject method of Java.io.ObjectOutputStream.
Note: The transient decorated field will be serialized at this time, depending on the writeobject.
If there are actually 5 elements, and the size of Elementdata is probably 10, then only 5 elements must be stored in the serialization, and the last five elements in the array are meaningless and do not need to be stored.
So the designer of ArrayList designed the Elementdata as transient, then serialized it manually in the WriteObject method, and serialized only those elements that were actually stored, not the entire array.

(4) Source code comment

/** * Constructed using a Collection * ArrayList a large number of related methods used in arrays */public ArrayList (Collection Collection) {elementdata =        Collection.toarray ();        size = Elementdata.length; if ((Object) (Elementdata). GetClass ()! = Object.class) {elementdata = arrays.copyof (elementdata, size, (elementdata)        . GetClass ()); }}/** * If the current array is larger than the number of data elements actually stored in the array, resizing the array * is used to reduce the capacity of the ArrayList to the current actual size, reducing storage capacity. * The variable Modcount is inherited by Abstraclist and records the number of times the list has been structured modified (structurally modified). * @Title: TrimToSize */public void TrimToSize () {Modcount++;int i = elementdata.length;if (Size < i) Elementdata = Array S.copyof (elementdata, size);} /** * Ensure the size of ArrayList * @Title: ensurecapacity * @param i */public void ensurecapacity (int i) {Modcount++;int j = Elementd Ata.length;if (i > J) {Object aobj[] = elementdata;int k = (J * 3)/2 + 1;if (K < i) k = I;elementdata = Arrays.copy Of (Elementdata, k);}} /** * Returns the subscript of the specified element, to distinguish whether the parameter is null * Note that ArrayList can be a */public int indexOf (Object obj) {if (obj = = nu) that can store nullll) {for (int i = 0; i < size; i++) if (elementdata[i] = = null) return I,} else {for (int j = 0; J < size; J + +) if (obj . Equals (Elementdata[j])) return J; return-1;} /** * uses the system's System.arraycopy method * This is a native method */public object[] ToArray (Object aobj[]) {if (Aobj.length < size) return (object[]) Arrays.copyof (Elementdata, size, (aobj). GetClass ()); System.arraycopy (((object) (Elementdata)), 0, ((object) (Aobj)), 0,size), if (aobj.length > Size) aobj[size] = null; return aobj;} /** * is related to serialization and transient processing */private void writeobject (ObjectOutputStream objectoutputstream) throws IOException {int i = Modcount;objectoutputstream.defaultwriteobject (); Objectoutputstream.writeint (elementdata.length); for (int j = 0; j < size; J + +) Objectoutputstream.writeobject (elementdata[j]); if (modcount! = i) throw new Concurrentmodificationexception (); Elsereturn;}

  

>> Summary

Applying static arrays in Java is prone to some errors, compared to

ArrayList can dynamically increase and decrease elements, flexibly set the size of the array, provides a variety of traversal methods, at design time as much as possible to consider the performance, most of the engineering development in the array will use ArrayList.

Java Collection Source learning Note (ii) ArrayList analysis

Related Article

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.