ArrayList, Vector Array set, arraylistvector

Source: Internet
Author: User

ArrayList, Vector Array set, arraylistvector

ArrayList:

■ Class definition

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • Inherits AbstractList and implements List. It is an array queue and provides related functions such as adding, deleting, modifying, and traversing.
  • Implement the RandmoAccess interface to achieve fast Random Access: quickly obtain element objects through the element serial number
  • Implement Cloneable interface, rewrite clone (), and clone (Shortest copy)
  • Implement the java. io. Serializable interface and support serialization

■ Global variables

/*** The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. any * empty ArrayList with elementData = EMPTY_ELEMENTDATA will be expanded to * DEFAULT_CAPACITY when the first element is added. * The underlying implementation of ArrayList is a dynamic array. objects do not need to be maintained during storage. java serialation provides persistence.
* Mechanism, we do not want this Object to be serialized, so use transient */private transient Object [] elementData;
/*** The size of the ArrayList (the number of elements it contains ). * array length: Pay attention to the concept of distinguishing the length (number of existing elements in the current array) and capacity (number of elements available in the current array) * @ serial */private int size; /*** The maximum size of array to allocate. some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in OutOfMemoryError: * Requested array size exceeds VM limit * maximum length allowed by the array; if it exceeds the threshold, a 'memory overflow exception' is reported. The terrible consequence is that the instance is down */private static final int MAX_ARRAY_SIZE = Integer. MAX_VALUE-8;

 

■ Constructor

/*** Constructs an empty list with the specified initial capacity. * Create an empty list of specified capacity * @ param initialCapacity the initial capacity of the list * @ throws IllegalArgumentException if the specified initial capacity is negative */public ArrayList (int initialCapacity) {super (); if (initialCapacity <0) throw new IllegalArgumentException ("Illegal Capacity:" + initialCapacity); this. elementData = new Object [initialCapacity];}
/*** Constructs an empty list with an initial capacity of ten. * default capacity: 10 */public ArrayList () {this (10 );}
/*** Constructs a list containing the elements of the specified collection, * in the order they are returned by the collection's iterator. * An error occurred while converting a Collection object to ArrayList * @ param c the collection whose elements are to be placed into this list * @ throws NullPointerException if the specified collection is null * /public ArrayList (Collection <? Extends E> c) {elementData = c. toArray (); // obtain the underlying dynamic array size = elementData. length; // obtain the length of the underlying dynamic array // c. toArray might (incorrectly) not return Object [] (see 6260652) if (elementData. getClass ()! = Object []. class) elementData = Arrays. copyOf (elementData, size, Object []. class );}

 

■ Main methods

-Add ()

  • From the source code, ArrayList generally inserts elements at the end and supports dynamic resizing.
  • Frequent insertion/deletion is not recommended because System. arraycopy () is very time-consuming to be called when you execute add ()/remove (). For frequent insertion/deletion scenarios, please use the sort list
/*** Appends the specified element to the end of this list. * use the tail insert method to insert new elements to the end of the array. * The error detection mechanism throws an exception, so directly return true * @ param e element to be appended to this list * @ return <tt> true </tt> (as specified by {@ link Collection # add }) */public boolean add (E e) {// adjust the capacity and modify the direction of the elementData array. When the array Length plus 1 exceeds the original capacity, ensureCapacityInternal (size + 1) will be automatically expanded; // Increments modCount !! Add is a structural modification of elementData [size ++] = e; // end insert, Length + 1 return true ;}
/*** Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any subsequent elements to * the right (adds one to their indices ). * Insert a new element to the specified subscript * this operation will cause all elements after the subscript to move backward (exercise caution when using this operation to avoid excessive array length) * @ param index at which the specified element is to be inserted * @ param element to be inserted * @ throws IndexOutOfBoundsExcep Tion {@ inheritDoc} */public void add (int index, E element) {// subscript boundary check. If the condition does not comply with the rule, 'indexoutofboundsexception 'rangeCheckForAdd (index) is thrown ); // adjust the capacity and modify the direction of the elementData array. When the array length is increased by 1 to exceed the original capacity, the system automatically expands ensureCapacityInternal (size + 1); // Increments modCount !! // Note that the displacement operation is performed on the original array. elements whose subscript is index + 1 move one System. arraycopy (elementData, index, elementData, index + 1, size-index); elementData [index] = element; // The current subscript value is size ++; // array Length + 1}

-EnsureCapacity (): Scale-up. The value 1.8 Has a default value.

// Judge public void ensureCapacity (int minCapacity) {int minExpand = (elementData! = Defacapcapacity_empty_elementdata) // any size if not default element table? 0 // larger than default for default empty table. it's already // supposed to be at default size.: DEFAULT_CAPACITY; if (minCapacity> minExpand) {ensureExplicitCapacity (minCapacity) ;}} private void ensureExplicitCapacity (int minCapacity) {modCount ++; // overflow-conscious code if (minCapacity-elementData. length> 0) grow (minCapacity );}

-Set ()/get (): directly operates the subscript pointer.

/*** Replaces the element at the specified position in this list with * the specified element. ** @ param index of the element to replace * @ param element to be stored at the specified position * @ return the element previusly at the specified position * @ throws IndexOutOfBoundsException {@ inheritDoc} */public E set (int index, E element) {rangeCheck (index); // check whether the inserted position is out of the range. E oldValue = elementData (index); elementData [index] = element; return oldValue ;}

/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);

return elementData(index);
}

-Remove (): the removal method is similar to add. It also uses System. arrayCopy (...)

/*** Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their indices ). ** remove the specified subscript element, at the same time, all array elements greater than the base object are moved to the left by a single place ** @ param index the index of the element to be removed * @ return the element that was removed from the list to return the original array element * @ throws IndexOutOfBoundsException {@ inheritDoc} */public E remove (int index) {rangeCheck (index); // subscript boundary check E oldValue = elementData (index); // obtain the current coordinate element fastRemove (int index); // here I modified the source code, use the fastRemove method directly, and return oldValue without changing the logic; // return the original array element}
/*** Removes the first occurrence of the specified element from this list, if it is present. * If the list does not contain the element, it is unchanged. * More formally, removes the element with the lowest index <tt> I </tt> such that * <tt> (o = null? Get (I) = null: o. equals (get (I) </tt> (if such an element exists ). * Returns <tt> true </tt> if this list contained the specified element * (or equivalently, if this list changed as a result of the call ). * directly remove an element: * If the element does not exist, it will not change. * If the element exists and is successfully removed, true is returned. Otherwise, false * If the element already exists, only Delete the element with the same name as the first occurrence: * For example, only remove the first occurrence of null (that is, the minimum occurrence of the subscript null) * @ param o element to be removed from this list, if present * @ return <tt> true </tt> if this list contained the specified element */public boolean remove (Object o) {// This value needs to be retrieved in order when the element is removed. if (o = null) {// ArrayList allows null when the array length is too long, extra null processing is required (only the first occurrence of null is processed) 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 ;}

-Encapsulate fastRemove ()

/** Private remove method that skips bounds checking and does not return the value removed. * The private method removes the subscript boundary check and does not return the result of the removal operation */private void fastRemove (int index) {modCount ++; // The remove operation is a structural change, modCount count + 1 int numMoved = size-index-1; // if (numMoved> 0) the length to be left shifted. // if the value is greater than the value of all array elements of the base object, the value is shifted to one System. arraycopy (elementData, index + 1, elementData, index, numMoved); elementData [-- size] = null; // Let gc do its work length-1 while accelerating gc}

■ Traversal and sorting

/*** Created by meizi on. * List <data type> sorting, traversing */public class ListSortTest {public static void main (String [] args) {List <Integer> nums = new ArrayList <Integer> (); nums. add (3); nums. add (5); nums. add (1); nums. add (0); // The traversal and deletion operations/* Iterator <Integer> iterator = nums. iterator (); while (iterator. hasNext () {Integer num = iterator. next (); if (num. equals (5) {System. out. println ("deleted element:" + num ); Iterator. remove (); // deletable} System. out. println (nums); * // sort tools/* Collections. sort (nums); // sort the array objects at the underlying layer, and traverse and compare them using ListIterator. replace them with System. out. println (nums); * // ② custom sorting method/* nums. sort (new Comparator <Integer> () {@ Override public int compare (Integer o1, Integer o2) {if (o1> o2) {return 1 ;} else if (o1 <o2) {return-1 ;}else {return 0 ;}}); System. out. println (nums); * // traverses sin Ce 1.8 Iterator <Integer> iterator = nums. iterator (); iterator. forEachRemaining (obj-> System. out. print (obj); // use lambda expressions/*** Objects to display various object methods, such as equals, toString, hash, toString * // * default void forEachRemaining (Consumer <? Super E> action) {Objects. requireNonNull (action); while (hasNext () action. accept (next ());}*/}}

 

■ List and Array Conversion

  • Object [] toArray (); ClassCastException may occur.
  • <T> T [] toArray (T [] contents) -- call toArray (T [] contents) to return T []
Public class ListAndArray {public static void main (String [] args) {List <String> list = new ArrayList <String> (); list. add ("java"); list. add ("C ++"); String [] strings = list. toArray (new String [list. size ()]); // use generics to avoid type conversion exceptions, because java does not support down-to-System Conversion. out. println (strings [0]);}

 

■ We will not detail the Vector, because it is not officially recommended: (JDK 1.0)

 

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.