Java ArrayList implementation and javaarraylist implementation

Source: Internet
Author: User

Java ArrayList implementation and javaarraylist implementation

About the implementation and principle of ArrayList, source: http://www.cnblogs.com/ITtangtang/p/3948555.html

I think he wrote very well. It's really good.

Make a record and summary.

Public class arraylist <E> {/*** elements of the Set **/private transient Object [] elementData;/** element size */private int size;

Defines a generic class, an array of objects, and a private variable to record the number of elements in the set. I don't know what to do if I have a private variable in the original text, I have not explained it or mentioned it. It's okay if I'm not using it.

1/** 2 * initialize 3 * @ param initialCapacity 4 */5 public arraylist (int initialCapacity) {6 super (); 7 if (initialCapacity <= 0) {8 // throw exception 9 throw new IllegalArgumentException ("initialization parameter cannot be less than 0"); 10} else {11 // initialize array 12 this. elementData = new Object [initialCapacity]; 13} 14} 15/** 16 * default initialization 17 */18 public arraylist () {19 this (10 ); 20} 21/** 22 * initialize 23 * @ param c Based on a Collection class a class that must inherit the Collection interface 24 */25 public arrayli St (Collection <? Extends E> c) {26 // initialize 27 elementData = c. toArray (); 28 size = elementData. length; 29 // if the array is not of any type, convert it to The Objec Type 30 if (elementData. getClass ()! = Object []. class) {31 elementData = Arrays. copyOf (elementData, size, Object []. class); 32} 33} 34

 

The three initialization Methods initialize the Array Based on the default size, initialize the Array Based on the given size, and pass a class that inherits the Collection interface for conversion assignment initialization.

1/** 2 * scale up the set 3 * @ param minCapacity 4 */5 public void ensureCapacity (int minCapacity) {6/** size of the current array */7 int oldCapacity = elementData. length; 8 if (minCapacity> oldCapacity) {9/** 10 * oldData is not used, but this is the reason for memory management and Arrays. the copyOf () method is not a thread-safe 11 * oldData references the elementData variable in the if life cycle, so it will not be reclaimed by GC 12 * When Arrays. when the copyOf () method copies elementData to newCapacity, it can prevent new memory or other threads from allocating the memory. The memory is occupied by elementData. Modify 13 * When the end is left if, the oldData cycle ends and 14 */15 objects are recycled. oldData [] = elementData; 16 int newCapacity = (oldCapacity * 3)/2 + 1; // increase by 50% + 117 if (newCapacity <minCapacity) 18 newCapacity = minCapacity; 19 // use Arrays. copyOf copies the elements of the set and generates a new array 20 elementData = Arrays. copyOf (elementData, newCapacity); 21} 22}

 

This is a core method. The expansion of a set is to compare the size of the minCapacity set and determine whether to resize the set. Arrays is used. copyOf () method for resizing,

This method copies the content of the first parameter to a new array. The size of the array is the second parameter and a new array is returned, the oldData variables are described in detail above.

 

1/** 2 * check whether the index is out of bounds. 3 * @ param index4 */5 private void RangeCheck (int index) {6 if (index> size | index <0) {7 throw new IndexOutOfBoundsException ("subscript exceeded, Index:" + index + ", Size:" + size); 8} 9}

 

Whether the retrieval of a lower mark is 1 /**

2 * add element 3 * add the specified element to the end of the set 4 * @ param e add element 5 * @ return 6 */7 public boolean add (E e) {8 ensureCapacity (size + 1); 9 elementData [size] = e; 10 size ++; 11 return true;
12}

 

Add an element, scale up first, assign a value, and add one to the element. Note:The size + 1 field does not add a value. Here we perform arithmetic operations, so we need to perform auto-increment only later.

1/** 2 * add element 3 * Add the element to the specified position 4 * @ param index the specified index subscript 5 * @ param element 6 * @ return 7 */8 public boolean add (int index, E element) {9 RangeCheck (index); 10 ensureCapacity (size + 1); 11 // elements whose length is size-Index starting from the index position in elementData, 12 // copy to the new elementData array starting from index + 1. 13 // Move the current element at this position and all subsequent elements to the right. 14 System. arraycopy (elementData, index, elementData, index + 1, size-index); 15 elementData [index] = element; 16 size ++; // element Plus 17 return true; 18}

The difference here is thatSystem. arraycopy (elementData, index, elementData, index + 1, size-index );

This is an internal method of c. It is explained in the original text in detail and will not be mentioned here. This is also the core of the entire ArrayList.Internal implementation principle of Arrays. copyOf ()

1/** 2 * add all elements 3 * add all elements in the collection to the end of the list according to the sequence returned by the iterator of the specified collection. 4 * @ param c 5 * @ return 6 */7 public boolean addAll (Collection <? Extends E> c) {8 Object [] newElement = c. toArray (); 9 int elementLength = newElement. length; 10 ensureCapacity (size + elementLength); 11 // starting from the subscript of newElement 0, elementLength elements, the subscript of elementData size 12 System. arraycopy (newElement, 0, elementData, size, elementLength); 13 size + = elementLength; 14 return elementLength! = 0; 15}

Basically, other methods perform different processing based on different situations. For example, you can pass in the data object through an interface and obtain the length for expansion, copy arraycopy to the new array

1/** 2 * specify the location, add all elements 3 * @ param index the subscript at the insert position 4 * @ param c the inserted element set 5 * @ return 6 */7 public boolean addAll (int index, Collection <? Extends E> c) {8 if (index> size | index <0) {9 throw new IndexOutOfBoundsException ("Index:" + index + ", Size:" + size ); 10} 11 Object [] newElement = c. toArray (); 12 int elementLength = newElement. length; 13 ensureCapacity (size + elementLength); 14 int numMoved = size-index; 15 // determine whether the inserted position is in the middle of the array 16 if (numMoved> 0) {17 // move all the elements behind the index insert position back 18 // insert numMoved elements starting with elementData index subscript to the index + e of elementData LementLength position 19 System. arraycopy (elementData, index, elementData, index + elementLength, numMoved); 20} 21 // Add the elementLength element starting from 0 in newElement to the position starting from elementData index 22 System. arraycopy (newElement, 0, elementData, index, elementLength); 23 size + = elementLength; 24 return elementLength! = 0; 25} 26 27/** 28 * specify the subscript value 29 * @ param index 30 * @ param element 31 * @ return 32 */33 public E set (int index, E element) {34 RangeCheck (index); 35 E oldElement = (E) elementData [index]; 36 elementData [index] = element; 37 return oldElement; 38} 39 40/** 41 * The subscript value is 42 * @ param index 43 * @ return 44 */45 public E get (int index) {46 RangeCheck (index ); 47 return (E) elementData [index]; 48} 49 50 /* * 51 * remove element 52 * @ param index 53 */54 public E remove (int index) {55 RangeCheck (index); 56 E oldElement = (E) elementData [index]; 57/** number of elements after the removed subscript */58 int numMoved = size-index-1; 59 // if it is in the array range, move 60 if (numMoved> 0) 61 System. arraycopy (elementData, index + 1, elementData, index, numMoved); 62 // remove 63 elementData [-- size] = null; 64 return oldElement; 65} 66 67/** 68 * remove 69 * @ param obj 70 Based on the element * @ Return 71 */72 public boolean remove (Object obj) {73 // Arraylist allows null to be stored. Therefore, you must judge and process 74 if (obj = null) {75 for (int index = 0; index <size; index ++) {76 if (elementData [index] = null) {77 remove (index); 78 return true; 79} 80} 81} else {82 for (int index = 0; index <size; index ++) {83 if (obj. equals (elementData [index]) {84 remove (index); 85 return true; 86} 87} 88} 89 return false; 90} 91 92/*** 93 * based on Subscript remove element 94 * @ param fromIndex start 95 * @ param toIndex end 96 */97 protected void removeRange (int fromIndex, int toIndex) {98 RangeCheck (fromIndex ); 99 RangeCheck (toIndex); 100 // number of elements to be moved: 101 int numMoved = size-toIndex; 102 // move the elements after toIndex to fromIndex103 System. arraycopy (elementData, toIndex, elementData, fromIndex, numMoved); 104 // The number of elements to be removed: 105 int newSize = size-(toIndex-fromIndex); 106 while (size! = NewSize) {107 elementData [-- size] = null; 108} 109} 110 111/** 112 * Adjusted the array capacity to 113 */114 public void trimToSize () {115 int leng = elementData. length; 116 if (size <leng) {117 Object [] old = elementData; 118 elementData = Arrays. copyOf (elementData, size); 119} 120} 121/** 122 * converts a set element to an array of 123 * @ return124 */125 public Object [] toArray () {126 return Arrays. copyOf (elementData, size); 127} 128 129 public <T> T [] toArray (T [] a) {130 if (. length <size) {131 return (T []) Arrays. copyOf (elementData, size,. getClass (); 132} 133 // copy the set elements to array a, 134 System. arraycopy (elementData, 0, a, 0, size); 135 if (. length> size) {136 for (int index = size; index <. length; index ++) {137 a [index] = null; 138} 139} 140 return a; 141}

Basically, operations on arrays and assignments are carried out using the c method. For details, you can view the original text. There are not many problems except the private variable in the original text, and the code can run perfectly, what Li should pay attention to and what is difficult?System, arraycopy, and Arrayist. copy () Methods
And the use of the oldData variable in the expansion method, this variable is really good, I do not know why to use it at the beginning, it will be explained at the end of the original 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.