Java collection: ArrayList (1)

Source: Internet
Author: User

A collection is a very important and basic piece of content in Java, because any data is essential is how the data is stored, the role of the collection is to organize and store data in a certain way. The collection here, part is more common, part is not commonly used but I personally have seen, some of the more similar collections (such as HashMap and Hashtable) only one, highlighting the difference between them.

Finally, to point out, for collections, I think there are four main points of concern:

1, whether to allow empty

2. Whether duplicate data is allowed

3, whether orderly, orderly means to read the order of data and the order of the data stored is consistent

4. is thread safe

I. Introduction of ArrayList

ArrayList is the most common and familiar collection class for every Java developer, as the name implies,ArrayList is a collection of arrays , with a table to see what the basic elements are in ArrayList :

Element Role
Private transient object[] elementdata; ArrayList is an array-based implementation, and Elementdata is the underlying array
private int size; ArrayList the number of elements inside, here to note that size is the number of calls to add, remove method to self-increment or decrement, so add a null into the arraylist,size will add 1

Four points of concern on the ArrayList answer

In the future, each article before the code, will first for a set of four points of concern in tabular form to do a solution:

Focus Point Conclusion
ArrayList whether NULL is allowed Allow
ArrayList whether duplicate data is allowed Allow
Whether the ArrayList is orderly Ordered
ArrayList is thread safe Non-thread safe

second, the bottom realization1) Adding elements

There is a code like this:

public static void Main (string[] args) {    list<string> List = new arraylist<string> ();    List.add ("the");    List.add ("111");}

Look at the bottom what will do, into the Add method of the source to look at:

Public boolean Add (E e) {    ensurecapacity (size + 1);  Increments modcount!!    elementdata[size++] = e;    return true;}

Do not go to the 2nd line of the Ensurecapacity method, this method is to expand the use of, the underlying actually call the Add method only to a certain location of the Elementdata to add a data, with a picture of the words are:

To say a word, I am so drawing a certain misleading. Elementdata should be stored in the heap in the memory of the elements of the reference, rather than the actual elements, so the painting gives a feeling that the Elementdata array is the actual elements stored inside, this is not very rigorous. But this painting is mainly for convenience, as long as you know the problem is good.

2)Expansion

Let's look at the default underlying array sizewhen constructing ArrayList:

Public ArrayList () {This    (10);}

Then there is a problem, the size of the underlying array is not enough to do? The answer is to expand, which is why always say that the bottom of the ArrayList is based on the implementation of dynamic array , the meaning of the dynamic array is that the underlying array size is not fixed, but based on the size of the added element to make a judgment, not enough words on the dynamic expansion, The code for expansion is in ensurecapacity:

public void ensurecapacity (int mincapacity) {modcount++;  int oldcapacity = Elementdata.length; if (Mincapacity > Oldcapacity) {    Object olddata[] = elementdata;    (oldcapacity * 3)/2 + 1;       if (Newcapacity < mincapacity)           newcapacity = mincapacity;       Mincapacity is usually close to size, so this is a win:       Elementdata = arrays.copyof (Elementdata, newcapacity); }}

When you see the expansion, multiply the element group size by 3, then divide by 2, and then add 1. Maybe some people want to ask why? We can think of:

1, if one-time expansion is too large, will inevitably cause the waste of memory space

2, if the one-time expansion of the expansion is not enough, then the next expansion of the operation will inevitably come soon, which will reduce the efficiency of the program, to know whether the expansion or performance of a more cost-effective operation

So the expansion and expansion of the JDK developers in time, space to do a trade-off, provide a more reasonable value. The last call to arrays's Copyof method is to copy the contents of the element group into the new array:

public static <T,U> t[] CopyOf (u[] original, int newlength, class<? extends t[]> NewType) {       t[] copy = ((O bject) NewType = = (Object) object[].class)           ? (t[]) new Object[newlength]           : (t[]) array.newinstance (Newtype.getcomponenttype (), newlength);       System.arraycopy (original, 0, copy, 0,                        math.min (Original.length, newlength));       return copy;}

This is the case with a picture:

3) Delete element

Let's take a look at the deleted action. ArrayList supports two ways to delete:

1. Delete according to subscript

2. Delete by element, which removes the first element in ArrayList that matches the element specified to be deleted

For ArrayList, the two methods of deletion are similar, and are the following piece of code for the call:

int nummoved = size-index-1;if (nummoved > 0)    system.arraycopy (Elementdata, index+1, Elementdata, Index,
    nummoved); Elementdata[--size] = null; Let GC do it work

In fact, the thing to do is two pieces:

1. Use the System.arraycopy method to move all the elements in the back position of the specified element forward one position

2, the element at the last position is specified as NULL, so that the GC can reclaim it

Let's say there's this code:

public static void Main (string[] args) {    list<string> List = new arraylist<string> ();    List.add ("111");    List.add ("222");    List.add ("333");    List.add ("444");    List.add ("555");    List.add ("666");    List.add ("777");    List.add ("888");    List.remove ("333");}

This is shown in the diagram:

4) Insert element

Take a look at the insert operation of the ArrayList, and the Add method is called by the insert operation, for example:

1 public static void main (string[] args) 2 {3     list<string> List = new Arraylist<string> (); 4     List.add ("111"); 5     List.add ("222"), 6     list.add ("333"), 7     list.add ("444"), 8     list.add ("555"), 9     list.add ("666");     List.add ("777"),     List.add ("888"),     List.add (2, "the"),     System.out.println (list); 14}

There's a place to be wrong, the Add method in line 12th means inserting an element after the first element, like Line 12th, which inserts a 000 after the second element. A look at the running results also proves this:

[111, 222, 000, 333, 444, 555, 666, 777, 888]

Or look at what you did when you inserted it:

1 public void Add (int index, E element) {2 if (Index > Size | | | Index < 0) 3     throw new Indexoutofboundsexception (4     "Index:" +index+ ", Size:" +size "); 5     ensurecapacity (size+1);  Increments modcount!! 6 system.arraycopy (elementdata, index, Elementdata, index + 1, 7          size-index); 8 Elementdata[index] = element; 9 size ++;10}

When you see the insertion, follow the specified position, Take all elements starting from the specified position using the System.arraycopy method to make a whole copy, move backward one position (of course, first to use the Ensurecapacity method to judge, add an element after the array will not be large enough), and then specify the position of the element is set to the element to be inserted, complete the insertion into the operation. The diagram shows that this is the process:

iii. Extension of the problem1) Advantages and disadvantages of ArrayList

Summarize the pros and cons of ArrayList from a few of the above processes. The advantages of ArrayList are as follows:

1, ArrayList the bottom of the array implementation, is a random access pattern, plus it implements the Randomaccess interface, so the search is a get is very fast

2, ArrayList in order to add an element is very convenient, just add an element to the array

But ArrayList's shortcomings are also obvious:

1, When deleting elements, involves a copy of the element, if you want to copy a lot of elements, then it will be more expensive performance

2, when inserting elements, involves a copy of the element, if you want to copy a lot of elements, then it will be more expensive performance

Therefore,ArrayList is more suitable for sequentially added, randomly accessed scenarios .

2) The difference between ArrayList and vectors

ArrayList is thread-insecure, which is obvious because all of the methods in ArrayList are not synchronous and there is a certain thread-safety problem in concurrency. So what do we want to do with ArrayList and make it thread safe? One approach is to use the Collections.synchronizedlist method to turn your ArrayList into a thread-safe list, such as:

list<string> synchronizedlist = collections.synchronizedlist (list); Synchronizedlist.add ("AAA"); Synchronizedlist.add ("BBB"); for (int i = 0; i < synchronizedlist.size (); i++) {    System.out.println ( Synchronizedlist.get (i));}

Another method is vector, which is the thread-safe version of ArrayList, and its implementation of 90% and ArrayList are exactly the same, the difference is:

1, vector is thread-safe, ArrayList is thread non-security

2, the vector can specify the growth factor, if the growth factor is specified, then each time the new array size will be added to the original array size based on the growth factor, if you do not specify the growth factor, then the original array size * *, the source code is this:

int newcapacity = oldcapacity + ((capacityincrement > 0)? capacityincrement:oldcapacity);
3) Why is the elementdata of ArrayList modified with transient?

The last question, let's look at the array in ArrayList, is so defined:

Private transient object[] elementdata;

Do not know whether you have thought, why elementdata is used transient modified it? On this question, tell me what I think. Let's take a look at the definition of ArrayList:

public class Arraylist<e> extends abstractlist<e>        implements List<e>, Randomaccess, Cloneable, Java.io.Serializable

Seeing that ArrayList implements the serializable interface, which means that ArrayList can be serialized, elementdata with transient means I don't want the Elementdata array to be serialized. Why is this? because the serialization of the ArrayList, ArrayList inside the elementdata is not necessarily full , for example, Elementdata has 10 of the size, but I only use 3 of them, Is it necessary to serialize the entire elementdata? This is obviously not necessary, so the WriteObject method is overridden in ArrayList:

private void WriteObject (Java.io.ObjectOutputStream s)        throws java.io.ioexception{//Write out element count, and Any hidden stuffint expectedmodcount = Modcount;s.defaultwriteobject ();        Write out Array length       s.writeint (elementdata.length);    Write out all elements in the proper order.for (int i=0; i<size; i++)           s.writeobject (Elementdata[i]);    if (modcount! = expectedmodcount) {           throw new concurrentmodificationexception ();}    }

Call this method each time the serialization, first call the Defaultwriteobject () method to serialize the non-transient element in the ArrayList, Elementdata not to serialize it, and then traverse Elementdata, Serialize only those elements, such as:

1. Speed up the serialization process

2. Reduced file size after serialization

is a clever approach, if the development process in the future encounter this situation, it is worth learning, learn from a way of thinking.

Original address: http://www.cnblogs.com/xrq730/p/4989451.html.

Java collection: ArrayList (1)

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.