Graphic set 1: ArrayList, graphic set arraylist

Source: Internet
Author: User

Graphic set 1: ArrayList, graphic set arraylist

Preface

In this category, the set in Java will be written. Collections are very important and basic content in Java, because any data is essential to how the data is stored. The function of a set is to organize and store data in a certain way. Some of the collections written here are common, some are not commonly used, but I have seen them at ordinary times, and some similar collections (such as HashMap and Hashtable) only talk about one, highlight the differences between them.

Finally, we should point out that for collections, I think there are four main points of attention:

1. Whether null is allowed

2. Whether repeated data is allowed

3. Order or not

4. thread security?

 

ArrayList

ArrayList is the most common collection class that every Java developer is most familiar with. As its name suggests, ArrayList isImplemented in array formIn a table to see what basic elements are in the ArrayList:

Yuansu For use
Private transient Object [] elementData; ArrayList is an array-based implementation. elementData is the underlying array.
Private int size; The number of elements in the ArrayList. Note that the size is auto-incremented or auto-subtracted based on the number of times the add or remove methods are called. Therefore, a null value is added to the ArrayList, the size is also increased by 1.

 

Add Element

There is such a piece of code:

public static void main(String[] args){    List<String> list = new ArrayList<String>();    list.add("000");    list.add("111");}

Let's take a look at what the underlying layer will do. Go to the source code of the add method to see it:

1 public boolean add(E e) {2 ensureCapacity(size + 1);  // Increments modCount!!3 elementData[size++] = e;4 return true;5 }

First, ignore the ensureCapacity method of the 2nd rows. This method is used for expansion. The underlying layer actually adds a data to a location of elementData when calling the add method, it is shown in a figure as follows:

To put it another way, it is misleading to draw a picture like this. ElementData should store references of elements in the heap memory, rather than actual elements. This painting gives people the feeling that the elements in the elementData array are actually elements, which is not rigorous. But this painting is mainly for convenience, as long as you know this problem.

 

Resizing

When constructing an ArrayList, the default underlying array size is 10:

public ArrayList() {this(10);}

So there is a problem. What should I do if the size of the underlying array is insufficient? The answer is resizing, which is why the bottom layer of ArrayList is based onDynamic ArrayThe reason for implementation is that the underlying array size is not fixed, but determined based on the size of the added element. If not, the system dynamically expands, the resizing code is in ensureCapacity:

public void ensureCapacity(int minCapacity) {modCount++;int oldCapacity = elementData.length;if (minCapacity > oldCapacity) {    Object oldData[] = elementData;    int newCapacity = (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, divide it by 2, and Add 1. Some may ask why? We can consider:

1. If one-time resizing is too large, it will inevitably lead to a waste of memory space

2. If one-time expansion is not enough, the next expansion operation will inevitably arrive quickly, which will reduce the program running efficiency. You need to know whether expansion is a performance-consuming operation.

Therefore, the size of expansion is a reasonable value provided by JDK developers in terms of time and space. Finally, the copyOf method of Arrays is called to copy the content in the element group to the new array:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {       T[] copy = ((Object)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;}

The following figure is used:

Delete

Next, let's take a look at the delete operation. ArrayList supports two deletion methods:

1. Delete by subscript

2. Delete by element. This will delete the first element in the ArrayList that matches the specified element to be deleted.

For ArrayList, the two deletion methods are similar. The following code is called:

int numMoved = size - index - 1;if (numMoved > 0)    System.arraycopy(elementData, index+1, elementData, index,             numMoved);elementData[--size] = null; // Let gc do its work

In fact, we do two things:

1. Move all the elements at the end of the specified element to a position forward using the System. arraycopy method.

2. Specify the element at the last position as null so that gc can recycle it.

For example, there is a piece of 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");}

It is shown in the figure below:

Insert

Let's take a look at the insert operation of ArrayList. The insert operation also calls the add method, 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");10     list.add("777");11     list.add("888");12     list.add(2, "000");13     System.out.println(list);14 }

The add method of row 12th means to insert an element to the end of the element. For example, row 12th inserts a 000 value to the end of the second element. The running results also prove this point:

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

Let's take a look at what was done during insertion:

 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 the data is inserted, all elements starting from the specified position are copied using the System and arraycopy methods, move a position backward (of course, first use the ensureCapacity method to determine whether the array will not be large enough after an element is added), and then set the element at the specified position to the element to be inserted, the insert operation is completed. The following figure shows the process:

 

Advantages and disadvantages of ArrayList

The advantages and disadvantages of ArrayList are summarized in the above process. ArrayList has the following advantages:

1. ArrayList is implemented in arrays at the underlying layer.Random AccessMode, coupled with the implementation of the RandomAccess interface, so the search is very fast, that is, get

2. It is very convenient for ArrayList to add an element in sequence, just adding an element to the array.

However, the disadvantages of ArrayList are also obvious:

1. When deleting an element, it involves an element copy. If there are many elements to be copied, it will be performance-consuming.

2. When an element is inserted, it involves an element copy. If there are many elements to be copied, it will be performance-consuming.

Therefore,ArrayList is suitable for sequential addition and random access scenarios..

 

Differences between ArrayList and Vector

ArrayList is thread unsafe, which is obvious because all the methods in ArrayList are not synchronized, and thread security problems may occur in concurrency. So what should we do if we want to use ArrayList and make it thread safe? One method is to use the Collections. synchronizedList method to change your List to a thread-safe one, for example:

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. Its implementation of 90% is the same as that of ArrayList. The difference is:

1. the Vector is thread-safe, and the ArrayList is thread-unsafe.

2. Vector can specify the growth factor. If this growth factor is specified, the new array size will be added to the original array size each time during expansion; if the growth factor is not specified, the size of the original array x 2 is given. The source code is as follows:

int newCapacity = oldCapacity + ((capacityIncrement > 0) ?                                 capacityIncrement : oldCapacity);

 

Why does elementData of ArrayList be modified with transient?

For the last question, let's take a look at the array in ArrayList, which is defined as follows:

private transient Object[] elementData;

I wonder if you have ever wondered why elementData is modified using transient? Let me talk about this question. 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

We can see that ArrayList implements the Serializable interface, which means that ArrayList can be serialized. Modifying elementData with transient means that I do not want the elementData array to be serialized. Why? During the serialization of ArrayList, elementData in ArrayList may not be full. For example, elementData has a size of 10, but I only use three of them. Is it necessary to serialize the entire elementData? Obviously this is not necessary, so the writeObject method is rewritten 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 during each serialization. First call the defaultWriteObject () method to serialize non-transient elements in the ArrayList. elementData does not serialize it, And then traverses elementData to serialize only those elements, as shown in the following code:

1. Speed up serialization

2. The serialized file size is reduced.

It is a clever practice. If this problem is encountered in the development process in the future, it is also a way of thinking worth learning and learning from.

 

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.