[Learning] java-collection class-ArrayList, java -- arraylist

Source: Internet
Author: User
Tags addall concurrentmodificationexception

[Learning] java-collection class-ArrayList, java -- arraylist
1. ArrayList class
API document address:
Http://docs.oracle.com/javase/7/docs/api/
(The English language is very general. If you have any errors, please help us to point out and correct them. Thank you): implement the interface List interface through a variable array. All optional list operations are implemented, and all running elements are null. In addition to methods in the interface, a method operation array size is provided to store the array size in the list. (This class is equivalent to an individual and is not synchronized, that is, the thread is not secure)
Size, isEmpty, get. set. iterator an listIterator these operations run at a fixed time. The add operation runs at a fixed time in stages, that is, it takes O (n) Time to add n elements. All other operations run on a single thread (roughly speaking ). The constant factor is low compared to that forLinkedListImplementation
All arraylists have a capacity. Capacity is used to store the list of array elements. The capacity is always the same as the size of the array list. After the element is added to the ArrayList, the capacity will increase. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
Before adding a large number of elements, the application can use the ensureCapacity method to increase the instance capacity, which can reduce the number of incremental redistribution.
Note that the secondary implementation is not synchronized. If multiple threads access the same ArrayList instance at the same time, if at least one thread modifies the list, it must be synchronized with the external. (Modification refers to adding or adding one or more elements, or adjusting the support array. modifying only the value of an element is not a structure modification.) It is usually done through the encapsulated object method. If such an object method does not exist, it should be used
Collections. synchronizedList method. The best practice is to prevent other non-synchronous access lists during creation.
    List list = Collections.synchronizedList(new ArrayList(...));   The iterators returned by this class'siteratorAndlistIteratorMethods areFail-fast: If the list is structurally modified at any time after the iterator is created, in any way cannot through the iterator's ownremoveOraddMethods, the iterator will throwConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future .. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of your concurrent modification. Fail-fast iterators throwConcurrentModificationExceptionOn a best-effort basis. Therefore, it wocould be wrong to write a program that depended on this exception for its correctness:The fail-fast behavior of iterators shocould be used only to detect bugsThis class is a member of the java Collection class.  From the official introduction, we can know about the following situations: 1. the ArrayList source code is implemented through arrays (actually, the array is known by the class name array) 2. when adding new elements, the efficiency will be affected. Iterative access query operations will be fast 3. arrayList has a capacity value. The ensureCapacity method is used to set this capacity value to help arrayList optimization (because arrays in java are fixed values. If arrayList stores a large value, we should inform arrayList of arrays with more capacity in advance.) 4. arrayList is not on-site security. You can use Collections. synchronizedList helps synchronization. 5. fail-fast Mechanism2. Check the ArrayList class.The following four attributes are declared: prviate static final int DEFAULT_CATACITY = 10; // The default size is private static final Object [] EMPTY_ELEMENTDATA = {}; // It is an empty array private transient Object [] elementData; // There is an array, which is the array private int size of the ArrayList storage Object; // The number of elements is from the four attributes. The bottom layer of ArrayList is stored in elementData through the array structure. Q: 1. what is the purpose of declaring the attribute keyword transient? 2. Since the array elementData is available, the length can be obtained using. length. Why should we use size?3.Constructor:There are only three of them.Below:1. Assign the array length by yourself

    public ArrayList(int initialCapacity) {        super();        if (initialCapacity < 0)            throw new IllegalArgumentException("Illegal Capacity: "+                                               initialCapacity);        this.elementData = new Object[initialCapacity];    }
2. An empty array by default
    public ArrayList() {        super();        this.elementData = EMPTY_ELEMENTDATA;    }
3. Copy a Collection to the array. You can see that ArrayList copies the Collection to elementData.
    public ArrayList(Collection<? extends E> c) {        elementData = c.toArray();        size = elementData.length;        // c.toArray might (incorrectly) not return Object[] (see 6260652)        if (elementData.getClass() != Object[].class)            elementData = Arrays.copyOf(elementData, size, Object[].class);    }

 

  4. Operation Method: Operation Methods: add (E e), add (int index, E element), addAll (Collection <? Extends E> c), addAll (int index,Collection <? Extends E> c). You can check the source code.Because ArrayList is in the Operation Array, only one of these methods is described.   1. Add an element method
    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }
From the method body, we can see two operations, 1. Declare an array length, 2. assign values to the array subscript.     5. EnsureCapacity Method
Public void ensureCapacity (int minCapacity) {// determines whether an empty array is returned. If DEFAULT_CAPACITY is returned, it mainly tells you, do not set a capacity smaller than the default value when the ArrayList statement is not used. Int minExpand = (elementData! = EMPTY_ELEMENTDATA) // any size if real element table? 0 // larger than default for empty table. It's already supposed to be // at default size.: DEFAULT_CAPACITY; if (minCapacity> minExpand) {minute (minCapacity );}}
This method can be used when an element already exists in the ArrayList capacity. It is usually used when a large number of collections are continuously involved, because the system is told in advance to require a large number of Assembly elements, do not constantly create new arrays, replication consumes performance.6. TrimToSize method:
    public void trimToSize() {        modCount++;        if (size < elementData.length) {            elementData = Arrays.copyOf(elementData, size);        }    }
  ArrayList also provides the ability to adjust the capacity of the underlying array to the size of the actual elements saved in the current list. It can be implemented through the trimToSize method.  

7.Fail-Fast mechanism:

Pending...

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.