Java set learning (1)-arraylist

Source: Internet
Author: User

1. arraylist Overview:

Arraylist is a variable array implementation of the List interface. All optional list operations are implemented, which can include any element of null. In addition to the List interface, this class also provides some methods to internally store the size of the List array. (This is equivalentVectorClass, except this class is not synchronized .)

Each arraylist has a capacity that is used to store the array size of list elements. It is always equal to at least the size of the list. With the addition of elements to the arraylist, the capacity of the arraylist also increases. Before adding a large number of elements, the application can also use the ensurecapacity operation to increase the capacity of the arraylist instance, which can reduce the number of progressive redistribution.

Note that this implementation is not synchronous.If multiple threads access oneArraylistInstance, and at least one thread modifies the list from the structure, itRequiredMaintain external synchronization. This is generally done by synchronizing the objects that encapsulate the list. If such an object does not exist, useCollections.synchronizedListMethod to wrap the list.

Arraylist inherits abstractlist and implements the list, randomaccess, cloneable, and Java. Io. serializable interfaces:

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

An array of the object type is defined internally for storage. Transient means that the serialization is not performed, which is opposite to serializable.

private transient Object[] elementData;

Length of arraylist

private int size;

Three constructors:

Public arraylist (INT initialcapacity) {// specify the initial capacity of arraylist super (); If (initialcapacity <0) // The initial capacity cannot be less than 0, otherwise, an illegalargumentexception exception is thrown. Throw new illegalargumentexception ("illegal capacity:" + initialcapacity); this. elementdata = new object [initialcapacity];} public arraylist () {// by default, the initial capacity is 10 this (10);} public arraylist (collection <? Extends E> C) {// convert collection to arraylist elementdata = C. toarray (); // call the toarray () method to convert the collection to an array. If the collection is null, nullpointerexception size = elementdata is thrown. length; // C. toarray might (incorrectly) not return object [] (see 6260652) if (elementdata. getclass ()! = Object []. Class) elementdata = arrays. copyof (elementdata, size, object []. Class );}

The parameter is a collection constructor. The problem here is caused by the arrays. aslist () method. When arrays. aslist (T
T) in a method, the parameter type is a subclass of the object. For example, if the return value of the method is passed to the arraylist constructor as a parameter, toarray () is called during the execution of the constructor () because the clone () method is used, an array of the string [] type is returned instead of an array of the obejct [] type, execute the print method in the following code to obtain the type of the returned value. Adding an object to the toarray () returned object will throw an exception. Specific explanations can refer to the http://bugs.sun.com/bugdatabase/view_bug.do? Bug_id = 6260652

List <Object> List = new arraylist <Object> (arrays. aslist ("test1", "Test2"); // returns string [], and obejct [] type // system. out. println (arrays. aslist ("foo", "bar "). toarray (); // when an object is added to the List object, arraystoreexception list is thrown. set (0, new object ());

Trimtosize is used when the memory is insufficient:

Public void trimtosize () {modcount ++; // The number of times the list has been changed from the structure, indicating that the method modifies the list int oldcapacity = elementdata from the structure. length; If (size <oldcapacity) {// compare the length of the current elementdata with the size. If the size is small, change the elementdata length to size. Elementdata = arrays. copyof (elementdata, size );}}

Extended array length ensurecapacity: expands the length to 1.5 times + 1 of oldsize. If it is still long enough, the specified length is used.

Public void ensurecapacity (INT mincapacity) {modcount ++; // similar to trimtosize, the list int oldcapacity = elementdata is changed from the structure. length; If (mincapacity> oldcapacity) {object olddata [] = elementdata; int newcapacity = (oldcapacity * 3)/2 + 1; // if the specified parameter is greater than the original length, create an array of 1.5 times + 1 and add the elements to it. If (newcapacity <mincapacity) newcapacity = mincapacity; // If the length is not enough, use the length of the specified parameter. // mincapacity is usually close to size, so this is a win: elementdata = arrays. copyof (elementdata, newcapacity );}}

Returns the length of the arraylist:

public int size() {    return size;}

Determine whether arraylist is empty:

public boolean isEmpty() {    return size == 0;}

Find the subscript of the first occurrence of the specified object in arraylist:

Public int indexof (Object O) {// elementdata. length is different from size. If (O = NULL) {for (INT I = 0; I <size; I ++) // If the parameter is null, then, the arraylist will be traversed from the position where the subscript is 0 until the first element is found as the null value if (elementdata [I] = NULL) return I ;} else {for (INT I = 0; I <size; I ++) // If the parameter is not null, the elements in the arraylist that are equal to the specified parameter are traversed, returns the value of IF (O. equals (elementdata [I]) return I;} return-1; // If none are found,-1} is returned}

Find the subscript of the last occurrence of the specified object in arraylist:

public int lastIndexOf(Object o) {    if (o == null) {          for (int i = size-1; i >= 0; i--)               if (elementData[i]==null)                   return i;    } else {          for (int i = size-1; i >= 0; i--)               if (o.equals(elementData[i]))               return i;    }    return -1;}

Use equals to determine whether the element contains the specified parameter:

public boolean contains(Object o) {    return indexOf(o) >= 0;} 

Override the clone () method, that is, copy the array and reset modcount:

Public object clone () {try {arraylist <E> V = (arraylist <E>) super. clone (); V. elementdata = arrays. copyof (elementdata, size); // array copy v. modcount = 0; // reset return V;} catch (clonenotsupportedexception e) {// this shouldn't happen, since we are cloneable throw new internalerror ();}}

Convert to an array:

public Object[] toArray() {    return Arrays.copyOf(elementData, size);}

Toarray (T [] A): I don't quite understand what to do

public <T> T[] toArray(T[] a) {    if (a.length < size)         // Make a new array of a's runtime type, but my contents:         return (T[]) Arrays.copyOf(elementData, size, a.getClass());    System.arraycopy(elementData, 0, a, 0, size);    if (a.length > size)        a[size] = null;    return a;}

Check whether the specified parameter index is correct:

private void RangeCheck(int index) {    if (index >= size)         throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);}

If the specified index element is obtained, the indexoutofboundsexception will be thrown if the parameter is unreasonable:

public E get(int index) {    RangeCheck(index);    return (E) elementData[index];}

I always thought that the returned result of set is void. I did not understand it until today. The returned value is the element that is located in the specified index before replacement.

public E set(int index, E element) {    RangeCheck(index);    E oldValue = (E) elementData[index];    elementData[index] = element;    return oldValue;}

Add the specified element to the end of the list:

Public Boolean add (E) {ensurecapacity (size + 1); // increments modcount !! Elementdata [size ++] = E; // Add to the end of the list and return true ;}

Add the specified element to the specified index:

Public void add (INT index, e element) {If (index> size | index <0) throw new indexoutofboundsexception ("index:" + index + ", size: "+ size); ensurecapacity (size + 1); // increments modcount !! // Copy the list elements from index to last-1 to index + 1 to the last position of system. arraycopy (elementdata, index, elementdata, index + 1, size-index); elementdata [Index] = element; size ++ ;}

 

 

Related 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.