ArrayList Introduction
ArrayList is an array queue, which is the equivalent of a dynamic array. Its capacity can grow dynamically compared to an array in Java. It inherits from Abstractlist, implements the list, randomaccess, cloneable, java.io.Serializable these interfaces.
ArrayList inherited the Abstractlist and realized the list. It is an array queue that provides related additions, deletions, modifications, and traversal functions.
ArrayList implements the Randmoaccess interface, which provides a random access function. Randmoaccess is a list implemented in Java to provide quick access to the list. In ArrayList, we can quickly get the element object by the ordinal of the element, which is the fast random access. Later, we'll compare the efficiency of the list's "Quick Random access" and "access via iterator iterator."
ArrayList implements the Cloneable interface, which covers the function clone () and can be cloned.
ArrayList implements the Java.io.Serializable interface, which means that ArrayList supports serialization and can be transmitted through serialization.
Unlike vectors, operations in ArrayList are not thread-safe. Therefore, it is recommended that ArrayList be used in a single thread, while vectors or copyonwritearraylist can be selected in multiple threads.
Let's turn to the ArrayList source code to see some common method attributes, as well as some of the areas that need attention. ArrayList Property
The ArrayList property is mainly the current array length size, and the array of objects Elementdata array, in addition to a frequently used property is inherited from the abstractlist Modcount attributes, Represents the number of times the ArrayList collection was modified.
public class Arraylist<e> extends abstractlist<e> implements List<e>, Randomaccess, Cloneable, Serializable {
//serialization ID
private static final long serialversionuid = 8683452581122892189L;
Default initial capacity
private static final int default_capacity = ten;
An empty object
private static final object[] Empty_elementdata = new Object[0];
An empty object, if created using the default constructor, the default object content defaults to the value
private static final object[] Defaultcapacity_empty_elementdata = new Object[0] ;
The current data object is stored where the current object does not participate in the serialization of
transient object[] elementdata;
The current array length is
private int size;
Array maximum length
private static final int max_array_size = 2147483639;
Ellipsis method ...
}
ArrayList Constructors If the parameterless constructor does not pass in the argument, the default parameterless build method is used to create the ArrayList object, as follows:
Public ArrayList () {
this.elementdata = defaultcapacity_empty_elementdata;
}
Note: The length of the Elementdata in the ArrayList object we created at this time is 1,size is 0, and when the first add is made, Elementdata will become the default length: 10.
constructors with int typeIf the argument is passed, the initial array length of the specified ArrayList is represented, and if the incoming argument is greater than or equal to 0, the user's parameter is initialized, and if the user passes in a parameter less than 0, the exception is thrown, which is constructed as follows:
Public ArrayList (int initialcapacity) {
if (initialcapacity > 0) {
this.elementdata = new object[ Initialcapacity];
} else if (initialcapacity = = 0) {
this.elementdata = empty_elementdata;
} else {
throw new Illegalargumentexce Ption ("Illegal Capacity:" +
initialcapacity);
}
constructors with collection objects1 converts the collection object to an array, and assigns the address of the arrays to Elementdata. 2) Update the value of size, at the same time to determine size, if size is equal to 0, directly assign empty object Empty_elementdata address to Elementdata 3 if the value of size is greater than 0, The Arrays.copy method is executed to copy the contents of the collection object (which can be understood as a deep copy) into the Elementdata.
Note: This.elementdata = Arg0.toarray (); A shallow copy of the simple assignment performed here, so a arrays,copy is performed to make a deep copy
Public ArrayList (COLLECTION< extends e> c) {
elementdata = C.toarray ();
if (size = elementdata.length)!= 0) {
//C.toarray might (incorrectly) not return object[] ("=")
if 6260652 Mentdata.getclass ()!= object[].class)
elementdata = arrays.copyof (elementdata, size, object[].class);
Else {
//Replace with empty array.
This.elementdata = Empty_elementdata;
}
Add MethodAdd method has two, one is with one parameter, one is with two parameters, the following we explain each.
Add (E E) methodAdd's main execution logic is as follows: 1) To ensure that the array has used the length (size) plus 1 enough to save the next data 2 the modified number of times Modcount identity from 1, if the current array has used length (size) plus 1 after the current length of the array, then call the Grow method, the growth array, The Grow method changes the length of the current array to 1.5 times times the original capacity. 3 to make sure that the new data is stored locally, add the element to the location of size. 4) returns the Boolean value of the added success.
add Element Method Entry:
Public boolean Add (E e) {
ensurecapacityinternal (size + 1); Increments modcount!!
elementdata[size++] = e;
return true;
}
Make sure that the added element has local storage and that when the first element is added, the value of this.size+1 is 1, so the first addition will change the length of the current Elementdata array to 10:
private void ensurecapacityinternal (int mincapacity) {
if (Elementdata = = Defaultcapacity_empty_elementdata) {
mincapacity = Math.max (default_capacity, mincapacity);
}
Ensureexplicitcapacity (mincapacity);
}
Increase the number of modifications (Modcount) by 1, to determine whether the need to expand the length of the array, the criterion is to use the current required minimum length of the array compared to the length of the array, if greater than 0, then increase the length of the array.
private void ensureexplicitcapacity (int mincapacity) {
modcount++;
Overflow-conscious Code
if (Mincapacity-elementdata.length > 0)
grow (mincapacity);
}
If the current array has used space (size) plus 1 and is larger than the length of the array, increase the array capacity to 1.5 times times the original.
private void Grow (int arg0) {
int arg1 = this.elementData.length;
int arg2 = arg1 + (arg1 >> 1);
if (arg2-arg0 < 0) {
arg2 = arg0;
}
if (arg2-2147483639 > 0) {
arg2 = hugecapacity (arg0);
}
This.elementdata = arrays.copyof (This.elementdata, arg2);
}
Add (int index, E Element) method
This method is actually similar to the above add, the method can insert elements at the location of the element, at the specified position, as follows: 1 ensure that the number of inserts is less than or equal to the current array length, and is not less than 0, otherwise throws an exception 2 to ensure that the array has used length (size) plus 1 enough to save Next data 3) the number of changes (Modcount) is identified by 1, if the current array has used length (size) plus 1 is greater than the current array length, then call the Grow method, growth array 4) Grow method will change the length of the current array to 1.5 times times the original capacity. 5 After making sure there is enough capacity, use system.arraycopy to move the elements behind the position (index) you want to insert back one bit. 6 Store the new data content at the specified position (index) of the array
public void Add (int index, E element) {
Rangecheckforadd (index);
Ensurecapacityinternal (size + 1); Increments modcount!!
System.arraycopy (Elementdata, index, Elementdata, index + 1,
size-index);
Elementdata[index] = element;
size++;
}
Note: Using this method will cause the elements of the array after the specified position to be moved all over again, that is, to move one bit backward.
Get MethodReturns the element at the specified position.
Public E get (int index) {
Rangecheck (index);
Checkforcomodification ();
return ArrayList.this.elementData (offset + index);
}
Set Method
Make sure that the location of the set is less than the current array's length (size) and greater than 0, get the specified position (index) element, then place it in the oldvalue, place the element you want to set on the specified location (index), and then return the element oldvalue from the original position to the user.
Public E Set (int index, E element) {
Rangecheck (index);
E OldValue = elementdata (index);
Elementdata[index] = element;
return oldValue;
}
The contains method calls the IndexOf method, traverses each element in the array for comparison, returns True if the element is found, and returns false if it is not found.
Public Boolean contains (Object o) {return
indexOf (o) >= 0;
}
public int indexOf (Object o) {
if (o = = null) {for
(int i = 0; i < size; i++)
if (elementdata[i]==null) return
i;
} else {for
(int i = 0; i < size; i++)
if (o.equals (elementdata[i
)) return-1;
}
Remove Method according to the index remove
1 determine if the index is out of bounds
2 self-added modification times
3 Saves the element on the specified position (index) to OldValue
4 Move the element on the specified position (index) forward one
5 to empty the last element so that the garbage collector will recycle
6) return the original value oldvalue
Public E-Remove (int index) {
Rangecheck (index);
modcount++;
E OldValue = elementdata (index);
int nummoved = size-index-1;
if (nummoved > 0)
system.arraycopy (Elementdata, index+1, Elementdata, index,
nummoved);
Elementdata[--size] = null; Clear to let GC does its work return
OldValue;
}
Note: Calling this method does not reduce the length of the array, just empty the last array element.
Remove by Object
Loop through all the objects, get the index of the object, and call the Fastremove method to perform the remove operation
public boolean remove (Object o) {
if (o = = null) {for
(int index = 0; index < size; index++)
if (ELEMENTDA Ta[index] = = null) {
fastremove (index);
return true;
}
else {for
(int index = 0; index < size; index++)
if (O.equals (Elementdata[index))) {
fastremove (index); C11/>return true;
}
}
return false;
}
Navigate to the element index that requires remove, first move the element following the index to the front (call System.arraycooy implementation), and then empty the last element.
private void Fastremove (int index) {
modcount++;
int nummoved = size-index-1;
if (nummoved > 0)
system.arraycopy (Elementdata, index+1, Elementdata, index,
nummoved);
Elementdata[--size] = null; Clear to let GC does its work
}
The clear method adds an operand (modcount), empty the elements within the array, waits for the garbage collector to collect, and does not reduce the array capacity.
public void Clear () {
modcount++;
Work for
(int i = 0; i < size; i++)
elementdata[i] = null;
size = 0;
}
Sublist Method
We see that the code creates an internal class Sublist object in the ArrayList class, and the first parameter in the passed value is actually interpreted as returning a partial view of the current list, where the data content is actually pointing to the same place, If you modify the contents of the sublist return, then the original list will also change.
Public list<e> sublist (int arg0, int arg1) {
Sublistrangecheck (arg0, arg1, this.size);
Return to New Arraylist.sublist (this, 0, arg0, arg1);
}
TrimToSize Method 1 The number of modifications plus 1 2 removes the free space (including null values) from the elementdata, such as: the length of the array is 10, where only the first three elements are values, and the other is empty, then the length of the array is changed to 3 after the method is called.
public void TrimToSize () {
modcount++;
if (Size < Elementdata.length) {
Elementdata = (size = = 0)
? Empty_elementdata
: arrays.copyof (elementdata, size);
}
Iterator Method The Interator method returns an inner class that, because the creation of the inner class defaults to the external this pointer, can invoke the properties of the outer class.
Public iterator<e> iterator () {return
new Itr ();
}
In general, after calling the iterator, we will use iterator to do the traversal, where we use next to do the traversal, there is a need to pay attention to, that is, call next, may cause concurrentmodificationexception, This exception occurs when the number of changes is inconsistent with the expected number of changes (the number of times the iterator method is invoked), and we look at the code implementation in detail:
@SuppressWarnings ("unchecked") public
E next () {
checkforcomodification ();
int i = cursor;
if (i >= size)
throw new Nosuchelementexception ();
object[] Elementdata = ArrayList.this.elementData;
if (i >= elementdata.length)
throw new Concurrentmodificationexception ();
cursor = i + 1;
Return (E) Elementdata[lastret = i];
}
Expectedmodcount This value is determined when the user invokes the iterator method of ArrayList, but after that the user add, or remove the element of ArrayList, then Modcount will change, then the value will be unequal , a Concurrentmodificationexception exception is thrown, which is a more common exception in multi-threaded usage.
final void Checkforcomodification () {
if (modcount!= expectedmodcount)
throw new Concurrentmodificationexception ();
}
System.arraycopy Method
| Parameters |
Description |
| Src |
Original array |
| Srcpos |
Original array |
| Dest |
Destination array |
| Destpos |
The starting position of the target array |
| Length |
The number of array elements to copy |
Arrays.copyof MethodOriginal-the array to copy
Newlength-The length of the replica to be returned
NewType-type of replica to be returned
In fact, arrays.copyof is also the bottom of the call System.arraycopy implementation of the source code as follows:
Basic data types (other similar byte,short Public
Static int[] copyof (int[] original, int newlength) {
int[] copy = new Int[newlength];
System.arraycopy (original, 0, copy, 0,
math.min (Original.length, newlength));
return copy;
}
Summary
ArrayList is relatively simple in general, but ArrayList has the following features:
ArrayList itself implements the method of serialization and deserialization because it implements private void WriteObject (Java.io.ObjectOutputStream s) and private void ReadObject ( Java.io.ObjectInputStream s) method ArrayList based on an array, no capacity limit (can be expanded) to add elements may have to be expanded (so it is best to make a judgment), delete elements do not reduce capacity (if you want to reduce capacity, trimtosize ( ), when the element is deleted, the deleted location element is set to NULL, and the next GC reclaims the memory space of those elements . Thread unsafe Add (int index, E Element): When you add an element to a specified position in an array, you need to copy the position and all of its following elements back one get (int index): Gets the element at the specified location, directly from the index (O (1)) Remove (object o) need to traverse array remove (int index) do not need to traverse the array, just to determine whether the index is eligible, more efficient than remove (object O) high contains (E) need to traverse the array Using iterator traversal may cause multithreaded exceptions