Java Collection Series 03 ArrayList details (source parsing) and usage examples

Source: Internet
Author: User

Overview

In the previous chapter, we learned about the architecture of collection. At the beginning of this chapter, we explain the specific implementation class of collection, first of all, to explain the list, and the list of ArrayList is most commonly used. Therefore, we explain ArrayList in this chapter. First of all, a general understanding of ArrayList, then learn its source code, and finally through an example to learn how to use it. The content includes:
The 1th part of ArrayList introduction
Part 2nd ArrayList data structure
Part 3rd ArrayList source parsing (based on jdk1.6.0_45)
Part 4th ArrayList traversal mode
Part 5th ToArray () exception
Part 6th ArrayList Example

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3308556.html

Part 1th introduction of ArrayList

ArrayList Introduction

ArrayList is an array queue , which is equivalent to a dynamic array . Its capacity can grow dynamically compared to the array in Java. It inherits from the Abstractlist, implements the list, randomaccess, cloneable, java.io.Serializable these interfaces.

ArrayList inherits the Abstractlist and implements the list. It is an array queue that provides related additions, deletions, modifications, and traversal functions.
The ArrayList implements the Randmoaccess interface, which provides a random access function. randmoaccess is used in Java to be implemented by the list, providing quick access to the list. In the ArrayList, we can quickly get the element object by the ordinal of the element, which is fast random access. Later, we compare the efficiency of the list's "Fast Random Access" and "access via iterator iterators".

ArrayList implements the Cloneable interface, which covers the function clone () and can be cloned.

The ArrayList implements the Java.io.Serializable interface, which means that the ArrayList supports serialization and can be transmitted by serialization.

Unlike vectors,operations in ArrayList are not thread-safe ! Therefore, it is recommended that you use ArrayList in a single thread, and you can select vectors or copyonwritearraylist in multiple threads.

ArrayList constructor function

The default constructor ArrayList ()//capacity is the default capacity size of ArrayList. When capacity is insufficient due to increased data, the capacity adds half of the previous capacity. ArrayList (int capacity)//Create a arraylistarraylist that contains Collection (collection<? extends e> Collection)

ArrayList's API

Collection defined in Apiboolean Add (E object) Boolean AddAll (collection<? extends e> Collection) v OID Clear () Boolean contains (Object object) Boolean Containsall (collection<?> C Ollection) Boolean equals (Object object) int Hashcode () boolean isEmpty () iterator< E> iterator () boolean remove (Object object), Boolean RemoveAll (collection<?> collect Ion) Boolean Retainall (collection<?> Collection) int size () <T> t[] Toarr Ay (t[] array) object[] ToArray ()//Abstractcollection defined in apivoid Add (int location, E Object) Boole                 An AddAll (int. location, collection<? extends e> Collection) E get (int. location) int  IndexOf (Object object) int LastIndexOf (Object object) listiterator<e> listiterator (int Location) LISTITERATOR&LT E> listiterator () e Remove (int location) e Set (Int. location, E object) LIST&LT;E&G             T sublist (int start, int end)//ArrayList new Apiobject clone () void ensurecapacity (int minimumca pacity) void TrimToSize () void removerange (int fromIndex, int toindex)

part 2nd ArrayList data Structure

The inheritance relationship of ArrayList

Java.lang.Object   ?     Java.util.abstractcollection<e>         ?     Java.util.abstractlist<e>               ?     Java.util.arraylist<e>public class Arraylist<e> extends abstractlist<e>        implements List<e Randomaccess, cloneable, java.io.Serializable {}

ArrayList and collection relations such as :

The ArrayList contains two important objects: Elementdata and size.

Elementdata is an array of type "object[" that holds the elements added to ArrayList. In fact, Elementdata is a dynamic array, and we can execute its initial capacity through the constructor ArrayList (int initialcapacity), if it is initialcapacity through a constructor without arguments ArrayList () To create a ArrayList, the Elementdata capacity defaults to 10. Elementdata array size will be based on the growth of ArrayList capacity and dynamic growth, specific growth mode, please refer to the source code analysis in the Ensurecapacity () function.

() size is the actual size of the dynamic array.

Part 3rd ArrayList source parsing (based on jdk1.6.0_45)

In order to better understand the principle of ArrayList, the following ArrayList source code to make an analysis. ArrayList is implemented by arrays, and the source code is easier to understand.

View Code

Summary :
ArrayList actually saves the data through an array . When we construct ArrayList, if we use the default constructor, the default capacity size of ArrayList is ten.
(02) When the ArrayList capacity is insufficient to accommodate all elements, ArrayList will reset the capacity: New capacity = "(Raw capacity x3)/2 + 1".
ArrayList's clone function, which is to clone all the elements into an array.
(ArrayList) the way to implement Java.io.Serializable. When writing to the output stream, write "capacity", then write "every element", read "capacity" and read "every element" in turn when the input stream is read.

Part 4th ArrayList traversal mode

ArrayList supports 3 types of traversal methods

(01) The first, traversed by an iterator . That is, through the iterator to traverse.

Integer value = Null;iterator iter = List.iterator (); while (Iter.hasnext ()) {    value = (Integer) iter.next ();}

(02) The second kind, random access, through the index value to traverse.
Because ArrayList implements the Randomaccess interface, it supports random access to elements through indexed values.

Integer value = null;int size = List.size (); for (int i=0; i<size; i++) {    value = (Integer) list.get (i);        }

(03) The third type, forloop traversal . As follows:

Integer value = null;for (integer integ:list) {    value = integ;}

The following example compares the efficiency of these 3 ways , with the example code (ARRAYLISTRANDOMACCESSTEST.JAVA) as follows:

View Code

Operation result :

Iteratorthroughrandomaccess:3 ms
Iteratorthroughiterator:8 ms
Iteratorthroughfor2:5 ms

Thus, when traversing ArrayList, using random access (that is, access by index ordinal) is the most efficient, and using iterators is the least efficient!

Part 5th ToArray () exception

When we call ToArray () in ArrayList, we may have encountered a situation where the "Java.lang.ClassCastException" exception was thrown. Let's talk about what's going on here.

ArrayList provides 2 toarray () functions:

Object[] ToArray () <T> t[] ToArray (t[] contents)

Calling the ToArray () function throws an "java.lang.ClassCastException" exception, but calling ToArray (t[] contents) returns to t[normally.

ToArray () throws an exception because ToArray () returns an array of object[] and converts object[] to another type (such as object[] to be converted into integer[]) and throws " Java.lang.ClassCastException "Exception, because Java does not support downward transformation . Specific can refer to the previous Arraylist.java source code Introduction section of the ToArray ().
The solution to this problem is to call <T> t[] ToArray (t[] contents), not object[] ToArray ().

Calls to ToArray (t[] contents) return t[] can be implemented in several ways.

ToArray (t[] contents) Call mode a public static integer[] VectorToArray1 (arraylist<integer> v) {    integer[] NewText = new Integer[v.size ()];    V.toarray (NewText);    return NewText;} ToArray (t[] contents) call mode two. most commonly used! public static integer[] VectorToArray2 (arraylist<integer> v) {    integer[] NewText = (integer[]) V.toarray (new integer[0]);    return NewText;} ToArray (t[] contents) Call method three public static integer[] VectorToArray3 (arraylist<integer> v) {    integer[] NewText = new Integer[v.size ()];    Integer[] Newstrings = (integer[]) V.toarray (newtext);    return newstrings;}

Part 6th ArrayList Example

This article introduces the usage of common APIs in ArrayList through an example (Arraylisttest.java).

View Code

Operation result :

The first element is:5arraylist size=: 4ArrayList contains 3 is:falsenext is:5next is:10next is:2next is:4str:5str: 10str:2str:4arraylist is Empty:true

Java Collection Series 03 ArrayList details (source parsing) and usage examples

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.