Java ArrayList source Code anatomy

Source: Internet
Author: User
Tags addall

Turn from:

Java ArrayList source Code anatomy

General Introduction

ArrayList implements the List interface, which is the sequential container, where the elements hold the same data as in the order in which they are placed, allowing the elements to be placed and the null underlying to be implemented by arrays . Except that the class does not implement synchronization, the rest is roughly the same as the Vector . Each ArrayList has a capacity (capacity) that represents the actual size of the underlying array, and the number of stored elements in the container cannot be more than the current capacity. When adding elements to a container, if the capacity is insufficient, the container automatically increases the size of the underlying array. As mentioned earlier, the Java generics are just the syntax sugar provided by the compiler, so the array here is an object array so that it can accommodate any type of object.

Size (), IsEmpty (), Get (), set () methods can all be done in constant time, the time overhead of the Add () method is related to the insertion position, and the time overhead of the AddAll () method is proportional to the number of elements added. The remaining methods are mostly linear time.

For efficiency, ArrayList does not implement synchronization (synchronized), and if multiple threads are required for concurrent access, users can synchronize manually or use vectors instead.

Method anatomy Set ()

Since the bottom layer is an array of ArrayList set() methods it becomes very simple to assign values directly to the specified position of the arrays.

public E set(int index, E element) { rangeCheck(index);//下标越界检查 E oldValue = elementData(index); elementData[index] = element;//赋值到指定位置,复制的仅仅是引用 return oldValue;}
Get ()

get()The method is also very simple, the only thing to note is that because the underlying array is object[], the type conversion is required after the element is obtained.

public E get(int index) { rangeCheck(index); return (E) elementData[index];//注意类型转换}
Add ()

Unlike the vector of C + +,ArrayList has no method, the bush_back() corresponding method is add(E e) ,ArrayList also has no insert() method, the corresponding method is add(int index, E e) . Both of these methods add new elements to the container, which may cause capacity to be insufficient, so the remaining space checks are required before the element is added, and is automatically scaled if needed. The scaling operation is ultimately grow() done through methods.

Private void Grow(int  mincapacity) {int oldcapacity = Elementdata.int newcapacity = oldcapacity + (oldcapacity >> 1) ; //original 3 times times if (NewCapacity- Mincapacity < 0) newcapacity = mincapacity; if (newcapacity-max_array_size > 0) newCapacity = Span class= "Fu" >hugecapacity (mincapacity); Elementdata = Arrays. copyof (Elementdata, newcapacity); //expand Space and copy}          

Since the Java GC automatically manages memory, there is no need to consider the issue of source array deallocation.

After the space problem is solved, the insertion process becomes very simple.

add(int index, E e)You need to move the element first and then complete the insert operation, which means that the method has a linear time complexity.

AddAll ()

addAll()Method can add more than one element at a time, depending on the location there are also two, one is added at the end of the addAll(Collection<? extends E> c) method, one is to start the insertion from the specified location addAll(int index, Collection<? extends E> c) method. Similar to the add() method, a space check is required before insertion and is automatically expanded if necessary, and if inserted from a specified location, there is also a case for moving the element.
addAll()The time complexity is not only related to the number of elements inserted, but also to the location of the insertion.

Remove ()

remove()The method also has two versions, one is to remove(int index) delete the element at the specified location, and the other is to remove(Object o) delete the first satisfied o.equals(elementData[index]) element. The delete operation is add() the inverse of the operation and requires that the element after the delete point be moved forward one position. It is important to note that in order for the GC to work, you must explicitly assign a value to the last location null .

PublicEremove (int index) {rangecheck (index); modcount++; E oldValue = elementdata (index); int nummoved = size-index-1; if (nummoved > 0) system.+1, Elementdata, Index, nummoved); Elementdata[--size] = null; //clear reference to this location, let GC function  return oldValue;}               

About Java GC It is important to note that having a garbage collector does not necessarily mean there will be no memory leaks . The object can be GC based on whether there is a reference to it, the above code if not manually assigned null value, unless the corresponding position is overridden by other elements, the original object will never be recycled.

Other:

Java Collections Framework Overview Java Arraydeque Source code anatomy java linkedlist source code anatomy Java hashset and HashMap source analysis of the clearest red and black tree explanation (on)

Java ArrayList source Code anatomy

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.