The System.Collections.ArrayList class is a special array. By adding and removing elements, the length of the array can be changed dynamically.
one. advantage
1. Supports automatic size change function
2. Flexible insertion of elements
3. Flexible deletion of elements
two. limitation
Compared with ordinary arrays, the speed is slightly worse
three. Add elements
1. publicvirtualintAdd(objectvalue);
Add object to the end of ArrayList
ArrayList aList = new ArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");The content is
abcde
2. publicvirtualvoidInsert(intindex,objectvalue);
Insert element into the specified index of ArrayList
ArrayList aList = new ArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.Insert(0,"aa");The result is
aaabcde
3. publicvirtualvoidInsertRange(intindex,ICollectionc);
Insert an element in the collection into the specified index of the ArrayList
ArrayList aList = new ArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");ArrayList list2 = newArrayList();list2.Add("tt");list2.Add("ttt");aList.InsertRange(2,list2);The result is
abtttttcde
Four. delete
1. publicvirtualvoidRemove(objectobj);
Remove the first match of a specific object from an ArrayList, note that it is the first one
ArrayList aList = new ArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.Remove("a");The result is
bcde
2. publicvirtualvoidRemoveAt(intindex);
Removes elements at the specified index of ArrayList
aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.RemoveAt(0);The result is
bcde
3. publicvirtualvoidRemoveRange(intindex,intcount);
Removes a range of elements from the ArrayList. Index represents the index, count represents the number starting from the index
aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.RemoveRange(1,3);The result is
Copy the code as follows:ae
4. publicvirtualvoidClear();
Remove all elements from ArrayList.
five. Sort
1.publicvirtualvoidSort();
Sort elements in an ArrayList or part of it.
ArrayListaList=newArrayList();aList.Add("e");aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");DropDownList1.DataSource=aList;//DropDownListDropDownList1;DropDownList1.DataBind();The result is
eabcd
ArrayListaList=newArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.Sort();//Sorting DropDownList1.DataSource=aList;//DropDownListDropDownList1;DropDownList1.DataBind();The result is
abcde
2.publicvirtualvoidReverse();
Reverses the order of elements in an ArrayList or part of it.
ArrayListaList=newArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");aList.Reverse();//Reverse DropDownList1.DataSource=aList;//DropDownListDropDownList1;DropDownList1.DataBind();The result is
edcba
six. Find
1.publicvirtualintIndexOf(object);
2.publicvirtualintIndexOf(object,int);
3.publicvirtualintIndexOf(object,int,int);
Returns the zero-based index of the first match of an ArrayList or part of it. No return -1 was found.
ArrayList aList = new ArrayList(); aList.Add("a"); aList.Add("b"); aList.Add("c"); aList.Add("d"); aList.Add("e"); intnIndex=aList.IndexOf("a");//1 nIndex=aList.IndexOf("p");//Not found, -1 4.publicvirtualintLastIndexOf(object);
5.publicvirtualintLastIndexOf(object,int);
6.publicvirtualintLastIndexOf(object,int,int);
Returns the zero-based index of the last match of an ArrayList or part of it.
ArrayList aList = new ArrayList(); aList.Add("a"); aList.Add("b"); aList.Add("a");//Same as 0 aList.Add("d"); aList.Add("e"); intnIndex=aList.LastIndexOf("a");//The value is 2 instead of 0 7.publicvirtualboolContains(objectitem);
Determines whether an element is in an ArrayList. Return true if included, otherwise return false
seven. other
1. publicvirtualintCapacity{get;set;}
Gets or sets the number of elements that an ArrayList can contain.
2. publicvirtualintCount{get;}
Gets the number of elements actually contained in the ArrayList.
Capacity is the number of elements that an ArrayList can store. Count is the number of elements actually contained in the ArrayList. Capacity is always greater than or equal to Count. If the Count exceeds Capacity when adding an element, the capacity of the list is doubled by automatically reallocating the internal array.
If the Capacity value is explicitly set, the internal array also needs to be reassigned to accommodate the specified capacity. If Capacity is explicitly set to 0, the common language runtime sets it to its default capacity. The default capacity is 16.
After calling Clear, Count is 0, and at this time Capacity cut is the default capacity of 16, not 0
3. publicvirtualvoidTrimToSize();
Set capacity to the actual number of elements in the ArrayList.
If you do not add new elements to the list, this method can be used to minimize the memory system overhead of the list.
To completely clear all elements in the list, call the Clear method before calling TrimToSize. Cutting off an empty ArrayList will set the ArrayList's capacity to the default capacity, not zero.
ArrayList aList = new ArrayList();aList.Add("a");aList.Add("b");aList.Add("c");aList.Add("d");aList.Add("e");//Count=5,Capacity=16,aList.TrimToSize();//Count=Capacity=5; 8. Source code analysis
An implementation class of the List interface, internally uses an array to store element values, which is equivalent to an array of variable size.
1. Signature
public class ArrayList<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, Serializable
You can see that ArrayList inherits the AbstractList abstract class, which implements most methods of the List interface. If you want to implement an immutable List, just inherit this class and implement the get(int) and size methods. If you want to implement a mutable List, you need to override set(int, E). In addition, if the size of List is variable, the add(int, E) and remove() methods must also be overridden.
2. Constructor
ArrayList provides three constructors:
ArrayList()ArrayList(Collection<? extends E> c)ArrayList(int initialCapacity)
The Collection interface convention that each collection class should provide two "standard" constructors, one is a constructor without parameters (the first one above), and the other is a constructor with a single parameter (the second one above). ArrayList also provides a third constructor that accepts an int value to set the initial size of ArrayLi (the default size is 10).
3. Related methods
trimToSizepublic void trimToSize() { modCount++; int oldCapacity = elementData.length; if (size < oldCapacity) { elementData = Arrays.copyOf(elementData, size); } }Used to reduce the capacity of ArrayList to its current actual size and reduce the storage capacity. The variable modCount is inherited from AbstractList, recording the number of times the List is structurally modified. The element of the ArrayList is actually stored in elementData, which is declared as: private transient Object[] elementData; variable size is the number of elements of the ArrayList. When size < oldCapacity, call the Arrays.copyOf method to achieve reduction.
4.indexOf and lasIndexOf
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 i; } return -1; }These two methods return the subscript of the specified element, and we want to distinguish whether the parameter is null. LastIndexOf is similar to indexOf, but searching from behind to front.
5. EnsureCapacity
public void ensureCapacity(int minCapacity) { if (minCapacity > 0) ensureCapacityInternal(minCapacity); }private void ensureCapacityInternal(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }This method ensures the size of the ArrayList
6.add and addAll
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++; } add(int index, E element) to add an element to the specified position. First, call rangeCheckForAdd to check whether the index is valid. If index > size || index < 0, an exception will be thrown. Then make sure the capacity is increased by 1, and call System.arraycopy to move the element starting from index one position backward. Finally, set the value at index to the added element. There is also an overloaded add(E e) method that directly adds the element to the end.
addAll(Collection<? extends E> c) and addAll(int index, Collection<? extends E> c) add all elements in the Collection to the end and the specified positions respectively.
7.remove and removeAll
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }The remove(Object o) method deletes the specified element. First, look for the element location, and then call fastRemove(index) to delete it. The code is as follows:
private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) //Move all the elements behind index+1 one position forward System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } The overloaded remove(int index) method is used to delete elements at the specified location. removeRange(int fromIndex, int toIndex) is used to delete all elements between the specified locations.
RemoveAll(Collection<?> c) and retainAll(Collection<?> c) codes are as follows:
public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); }public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); }They are all implemented by calling the batchRemove method, and their code is as follows:
private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }This method has two parameters. The first is the operation Collection and the second is a boolean value. By setting it to true or false, it selects whether to removeAll or retainAll. The statement in try puts the remaining ones between 0 and w, and then finally the second if in finally handles the space after w, and the first one is executed when c.contains() throws an exception.