Java 2 source code: Java. util. arraylist

Source: Internet
Author: User
Tags addall
Download related source code:
Java. util. arraylist
Java. util. abstractlist
Java. util. List

Arraylist is a variable-length array implementation of the List interface. All list operations are implemented and null values can be stored. Except for not synchronizing data, arraylist is basically equivalent to vector. Almost all methods are synchronized in the vector, but the arraylist only synchronizes writeobject and readobject. Other methods such as add (object) and remove (INT) are not synchronized.

1. Storage

Arraylist uses an array of objects to store elements.
Private transient object elementdata [];
Arraylist implements the java. Io. serializable interface. The transient indicates that this attribute does not need to be automatically serialized. In the writeobject () method, we will explain in detail why this is necessary.

2. add and remove

  1. Public BooleanAdd (ObjectO ){
  2. Ensurecapacity (size + 1 );// Increments modcount !!
  3. Elementdata [size ++] = O;
  4. Return True;
  5. }

Note that the ensurecapacity () method is used to ensure that the length of the elementdata array can accommodate a new element. The automatic variable length mechanism is described in detail.

  1. Public ObjectRemove (IntIndex ){
  2. Rangecheck (INDEX );
  3. Modcount ++;
  4. ObjectOldvalue = elementdata [Index];
  5. IntNummoved = size-index-1;
  6. If(Nummoved> 0)
  7. System. Arraycopy (elementdata, index + 1, elementdata, index,
  8. Nummoved );
  9. Elementdata [-- size] =Null;// Let GC do its work
  10. ReturnOldvalue;
  11. }

Rangecheck () is used for border checks. Because arraylist uses an object array to store elements, you must move the following elements forward when deleting an element. When an element is deleted, the reference of the element in the elementdata array is set to null. The Garbage Collector is responsible for the destruction of the object.
The role of modcount is described in "synchronization in iterator ()" below.
Note: arraycopy () is a practical method provided by system when moving forward. In this example, we can see that system. the arraycopy () method can operate on the same array. This method is an native method. If you operate on the same array, it first copies the source part to a temporary array, copy the elements of the temporary array to the target position.

3. Automatic Variable Length Mechanism

When instantiating an arraylist, you can specify an initial capacity. This capacity is the initial length of the elementdata array. If you use:

  1. Arraylist list =NewArraylist ();

The default capacity is 10.

  1. PublicArraylist (){
  2. This(10 );
  3. }

Arraylist provides four add () methods,

  • Public Boolean add (Object O)
  • Public void add (INT index, object element)
  • Public Boolean addall (collection C)
  • Public Boolean addall (INT index, collection C)

In each add () method, an ensurecapacity (INT minicapacity) method is called first. This method ensures that the length of the elementdata array is not less than minicapacity. Arraylist's automatic variable length mechanism is implemented in this method.

  1. Public VoidEnsurecapacity (IntMincapacity ){
  2. Modcount ++;
  3. IntOldcapacity = elementdata.Length;
  4. If(Mincapacity> oldcapacity ){
  5. ObjectOlddata [] = elementdata;
  6. IntNewcapacity = (oldcapacity * 3)/2 + 1;
  7. If(Newcapacity <mincapacity)
  8. Newcapacity = mincapacity;
  9. Elementdata =New Object[Newcapacity];
  10. System. Arraycopy (olddata, 0, elementdata, 0, size );
  11. }
  12. }

From the implementation of this method, we can see that each expansion of arraylist is increased to 1.5 times the original size.
The implementation of each add () method is similar. The following describes the implementation of the add (object) method:

  1. Public BooleanAdd (ObjectO ){
  2. Ensurecapacity (size + 1 );// Increments modcount !!
  3. Elementdata [size ++] = O;
  4. Return True;
  5. }

4. Synchronization in iterator ()

In the parent class javasactlist, an int type attribute is defined: modcount, which records the number of structural changes in the arraylist.

  1. Protected Transient IntModcount = 0;

Add the modcount value to all methods in arraylist that involve structural changes, including: add (), remove (), addall (), removerange (), and clear. Each time these methods are called, the value of modcount is increased by 1.
Note: The modcount values of the add () and addall () methods are added in the ensurecapacity () method called.

The iterator () method in abstractlist (arraylist directly inherits this method) uses a private internal Member class itr to generate an itr object (iterator Interface) and returns:

  1. PublicIterator (){
  2. Return NewItr ();
  3. }

Itr implements the iterator () interface, which also defines an int-type attribute: expectedmodcount, which is assigned the value of the modcount attribute of the arraylist object during itr class initialization.

  1. IntExpectedmodcount = modcount;

Note: The internal Member class itr is also a member of the arraylist class. It can access all the attributes and methods of javasactlist. With this understanding, the implementation of the itr class is easy to understand.

In the itr. hasnext () method:

  1. Public BooleanHasnext (){
  2. ReturnCursor! = Size ();
  3. }

The abstractlist size () method is called to compare whether the current cursor position is out of bounds.

In the itr. Next () method, itr also calls the get (INT) method defined in javasactlist to return the elements at the current cursor:

  1. Public ObjectNext (){
  2. Try{
  3. ObjectNext = get (cursor );
  4. Checkforcomodification ();
  5. Lastret = cursor ++;
  6. ReturnNext;
  7. }Catch(IndexoutofboundsexceptionE ){
  8. Checkforcomodification ();
  9. Throw NewNosuchelementexception ();
  10. }
  11. }

Note that the checkforcomodification () method is called in the next () method to check the synchronization of the changes:

  1. Final VoidCheckforcomodification (){
  2. If(Modcount! = Expectedmodcount)
  3. Throw NewConcurrentmodificationexception ();
  4. }

Now the role of modcount and expectedmodcount should be very clear. When performing the drop generation operation on a collection object, the operation on the elements of the collection object is not limited. These operations include the add () or remove () operations that may cause the drop generation error () and other dangerous operations. Abstractlist uses a simple mechanism to avoid these risks. This is the role of modcount and expectedmodcount.

5. serialization support

Arraylist implements the java. Io. serializable interface, so the arraylist object can be serialized to persistent storage media. The main attributes of arraylist are defined as follows:

  • Private Static final long serialversionuid = 8683452584252892189l;
  • Private transient object elementdata [];
  • Private int size;

We can see that both serialversionuid and size will be automatically serialized to the media, but the elementdata array object is defined as transient. That is to say, all these elements in the arraylist will not be automatically serialized into the media. Why? Because the "elements" stored in the elementdata array are only a reference to these elements and are not real objects, serialization of an object reference is meaningless, because the serialization is for deserialization, When you deserialize, the reference of these objects cannot point to the original object. So we need to manually serialize the arraylist elements here. This is the role of writeobject.

  1. Private Synchronized VoidWriteobject (Java. Io.ObjectoutputstreamS)
  2. ThrowsJava. Io.Ioexception{
  3. // Write out element count, and any hidden stuff
  4. S. defaultwriteobject ();
  5. // Write out array Length
  6. S. writeint (elementdata.Length);
  7. // Write out all elements in the proper order.
  8. For(IntI = 0; I <size; I ++)
  9. S. writeobject (elementdata [I]);
  10. }

In this way, the element objects in the element array elementdata can be correctly serialized to the storage media.
The corresponding readobject () is also read from the input stream in the order of the writeobject () method:

  1. Private Synchronized VoidReadobject (Java. Io.ObjectinputstreamS)
  2. ThrowsJava. Io.Ioexception,Classnotfoundexception{
  3. // Read in size, and any hidden stuff
  4. S. defaultreadobject ();
  5. // Read in array length and allocate Array
  6. IntArraylength = S. readint ();
  7. Elementdata =New Object[Arraylength];
  8. // Read in all elements in the proper order.
  9. For(IntI = 0; I <size; I ++)
  10. Elementdata [I] = S. readobject ();
  11. }

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.