Use of ArrayList classes in Java and source code complete parsing _java

Source: Internet
Author: User
Tags addall

The System.Collections.ArrayList class is a special array. By adding and removing elements, you can dynamically change the length of the array.

A Advantages
1. Features that support automatic resizing
2. You can insert elements with flexibility
3. Can be flexible to delete elements

Two Limitations
compared to a normal array, the speed is worse.

Three adding elements
1. Publicvirtualintadd (Objectvalue);
Add an object to the end of the ArrayList

ArrayList alist = new ArrayList ();
Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");

Content is

Abcde

2. Publicvirtualvoidinsert (Intindex,objectvalue);
inserts an element into the ArrayList at the specified index

ArrayList alist = new ArrayList ();
Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");
Alist.insert (0, "AA");

Result is

Aaabcde

3. Publicvirtualvoidinsertrange (Intindex,icollectionc);
inserts an element from the collection into the ArrayList at the specified index

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);

Result is

Abtttttcde

Four Delete
1. Publicvirtualvoidremove (objectobj);
removes the first occurrence of a specific object from the ArrayList, noting that the first

ArrayList alist = new ArrayList ();
Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");
Alist.remove ("a");

Result is

Bcde

2. Publicvirtualvoidremoveat (Intindex);
removes the element at the specified index of the ArrayList

Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");
Alist.removeat (0);

Result is

Bcde

3. Publicvirtualvoidremoverange (Intindex,intcount);
removes a certain range of elements from the ArrayList. Index represents indexes, count indicates number starting at index

Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");
Alist.removerange (1,3);

Result is

Copy Code code as follows:
Ae

4. Publicvirtualvoidclear ();
Removes all elements from the ArrayList.

Five Sort
1. Publicvirtualvoidsort ();
sorts the elements in a 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 ();

Result is

Eabcd
Arraylistalist=newarraylist ();
Alist.add ("a");
Alist.add ("B");
Alist.add ("C");
Alist.add ("D");
Alist.add ("E");
Alist.sort ();//Sort
dropdownlist1.datasource=alist;//dropdownlistdropdownlist1;
Dropdownlist1.databind ();

Result is

Abcde

2.publicvirtualvoidReverse ();
reverses the order of elements in a 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 ();

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 occurrence of a value in a ArrayList or part of it. Not found return-1.

  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 occurrence of a value in a ArrayList or part of it.

  ArrayList alist = new ArrayList ();
  Alist.add ("a");
  Alist.add ("B");
  Alist.add ("a") and/or 0
  alist.add ("D")
  ; Alist.add ("E");
  Intnindex=alist.lastindexof ("a");//value 2 instead of 0

7. Publicvirtualboolcontains (Objectitem);
determines whether an element is in ArrayList. Contains return true, otherwise returns false

Seven Other
1. Publicvirtualintcapacity{get;set;}
Gets or sets the number of elements that ArrayList can contain.
2. Publicvirtualintcount{get;}
gets the number of elements actually contained in the ArrayList.
Capacity is the number of elements that ArrayList can store. Count is the number of elements that are actually contained in ArrayList. Capacity is always greater than or equal to count. If count exceeds capacity when the element is added, the capacity of the list doubles by automatically reallocating the internal array.
If the value of the capacity 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 the default capacity. The default capacity is 16.
After calling clear, Count is 0, and at this point capacity is the default capacity of 16, not 0
3. Publicvirtualvoidtrimtosize ();
sets the 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 overhead of the list.
To completely clear all the elements in the list, call the clear method before calling TrimToSize. Truncating an empty ArrayList sets the capacity of the ArrayList 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;

Eight. Source code Analysis
an implementation class of the List interface that internally uses an array to store element values, equivalent to a variable size array.

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 of the methods of the list interface. If you want to implement an immutable list, simply inherit the class and implement get (int) and the size method. If you want to implement a variable list, you need to overwrite set (int, E). Also, if the size of the list is variable, overwrite the add (int, E) and remove () methods.

2. Construction Device
the ArrayList provides three constructors:

ArrayList ()
ArrayList (collection<? extends e> c)
ArrayList (int initialcapacity)

Collection interface conventions, each collection class should provide two "standard" constructors, one with parameterless constructors (first above), and one with a single argument (type Collettion) (the second above). ArrayList also provides a third constructor that accepts an int value to set the initial size of the Arrayli (the default size is 10).

3. Related methods

TrimToSize public
void TrimToSize () {
    modcount++;
    int oldcapacity = elementdata.length;
    if (Size < oldcapacity) {
      elementdata = arrays.copyof (elementdata, size);
    }
  }

Used to reduce storage capacity by reducing the capacity of ArrayList to the current actual size. The variable Modcount is inherited by Abstraclist, and the number of structured modifications (structurally modified) is recorded for the list. The element in the elementdata that actually stores the ArrayList, declared in ArrayList as: Private transient object[] elementdata; Variable size is the number of elements ArrayList, when size When < 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-1;
  }

The two methods return the subscript of the specified element to distinguish whether the parameter is null. LastIndexOf and indexof are similar, just searching backwards.

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, and so is a win:
    Elementdata = arrays.copyof (Elementdata, newcapacity); 
   }

This method will ensure 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) adds elements to the specified location, first call Rangecheckforadd to check whether index is valid, if index > Size | | Index < 0 throws an exception. Then make sure that the capacity is plus 1, and call system.arraycopy to move the element starting from index one position. Finally, the value at index is set to the added element. Another overloaded add (E E) method is to add elements directly to the end.
AddAll (collection< extends e> c) and AddAll (int index, COLLECTION<? extends e> c) Adds all the elements in the collection to the end and the specified position, respectively.

7.remove and RemoveAll

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;
  }

The Remove (Object O) method deletes the specified element. The first is to find the element location, and then call Fastremove (index) deletion with the following code:

private void Fastremove (int index) {
    modcount++;
    int nummoved = size-index-1;
    if (nummoved > 0)
      //Index+1 The elements in the back move forward one position
      system.arraycopy (Elementdata, index+1, Elementdata, Index,
               nummoved);
    Elementdata[--size] = null; Let GC does its work
  }

The overloaded remove (int index) method deletes the element at the specified location. RemoveRange (int fromindex, int toindex) deletes all elements between the specified locations.
RemoveAll (collection<?> C) and Retainall (collection<?> c) code 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, whose code is as follows:

 private Boolean batchremove (Collection<?> C, Boolean complement) {final OBJEC
    t[] Elementdata = this.elementdata;
    int r = 0, w = 0;
    Boolean modified = false; try {for (; R < size; r++) if (C.contains (elementdata[r)) = = complement) elementdata[w++] = El
    EMENTDATA[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 it work for (int i = w; i < size; i++) elemen
        Tdata[i] = null;
        Modcount + = size-w;
        size = W;
      Modified = true;
  } return modified; }

This method has two parameters, the first is the collection of the operation, and the second is a Boolean value, which is either RemoveAll or Retainall by setting to True or false. The statement in try is to place the left in between 0 and W, and then in finally, the second if handles the space after W, and the first is executed when C.contains () throws an exception.

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.