Java Collection-arraylist

Source: Internet
Author: User
Tags addall throw exception

Always summarize the knowledge in the Java collection and don't know how to write. Think set too many things, write thin too difficult, write coarse and feel write bad. No matter how you feel or want to insist on writing the basics of this kind of things, in order to improve their programming base. Originally think of these already very familiar with these, recently saw some big God after found that the gap is too big, instant Meng, only in strengthening study.

What is ArrayList?

ArrayList is a dynamic array that implements the list interface, so-called dynamic refers to its size is variable. All optional list operations are implemented and all elements, including null , are allowed. In addition to implementing the list interface, this class provides methods to manipulate the size of the array used internally to store the list.

Since it is an array, there must be capacity. Each ArrayList object has a capacity, which is used to indicate how many data can be stored inside, that is, the size of the array (by default, 10). Of course, the dynamic will automatically increase, and every time we add data to it, it will be the expansion check, After checking the expansion will be enlarged to the original 1.5 times times, the expansion operation brings data to the new array re-copy, affecting performance, so if we know the specific amount of business data, in the construction of ArrayList can give ArrayList an initial capacity, which will reduce the data copying problem when expanding. Of course, before you add a large number of elements, the application can also use the ensurecapacity operation to increase the capacity of the ArrayList instance, which reduces the amount of incremental redistribution.

ArrayList the bottom of the implementation is not the same step, multi-threaded operation will have problems, this point we should pay attention to. You can insert duplicate data, and you can insert null.

Second, ArrayList source analysis

2.1. ArrayList definition

 Public class extends Abstractlist<e>        implements List<e>, randomaccess, Cloneable, java.io.Serializable

ArrayList definition, inherits Abstractlist, implements List<e>, Randomaccess, Cloneable, Java.io.Serializable, where Abstractlist implements the List Some of the location-related operations (such as Get,set,add,remove), are the first collection classes that implement random access methods, but do not support additions and replacements . Randomaccess represents whether the class supports random access,the Cloneable class supports cloning, and serializable supports serialization.

2.2. Using arrays at the bottom

Private static final Long Serialversionuid = 8683452581122892189l;//serialversionuid effect is to preserve version compatibility when serializing, That is, deserialization still preserves the uniqueness of the object during version upgrade.

Private transient object[] elementdata;//object array, transient keywords do not know the students themselves to check the data, with the Transient keyword variables will not be serialized. ArrayList the container, the basic operation is based on the array operation.

The size of the private int size;//array.

private static final int max_array_size = integer.max_value-8;//The maximum size of the array to allocate.

2.3. Constructor function

ArrayList has three constructors:

ArrayList (): default constructor that provides an empty list with an initial capacity of 10.

ArrayList (int initialcapacity): Constructs an empty list with the specified initial capacity.

ArrayList (collection<? extends e> c): Constructs a list of elements that contain the specified Collection, arranged in the order in which they are returned by the Collection iterator.

/*** Constructs an empty list with the specified initial capacity. *     * @paramInitial capacity of the initial capacity list *@throwsIllegalArgumentException throws an illegal exception if the specified initial capacity is negative. */     PublicArrayList (intinitialcapacity) {        Super(); if(Initialcapacity < 0)            Throw NewIllegalArgumentException ("Illegal capacity:" +initialcapacity);  This. Elementdata =NewObject[initialcapacity]; }    /*** Build an empty list with an initial capacity of 10. */     PublicArrayList () { This(10); }    /*** Constructs a list that contains the specified elements. * collection, in the order returned by the collection * iterators *@paramA collection of C whose elements will be placed in this list. * @throwsNullPointerException If the specified collection is NULL for throwing this null pointer exception. */     PublicArrayList (collection<?extendsE>c) {Elementdata=C.toarray ();//If it is empty, this will throw an exception size=elementdata.length; //C.toarray might (incorrectly) not return object[] (see 6260652)        if(Elementdata.getclass ()! = object[].class) Elementdata= arrays.copyof (elementdata, size, object[].class); }

2.4. Add method

ArrayList provides add (E e), add (int index, E Element), AddAll (collection<? extends e> c), AddAll (int index, collection< ? Extends E> c), set (int index, E Element) This five method to achieve ArrayList increase.

I will take one to speak, understand one, the other should all understand.

 Public BooleanAdd (e e) {ensurecapacityinternal (size+ 1);//increase the number of operationselementdata[size++] = e;//Put the value on the last one .        return true; }Private voidEnsurecapacityinternal (intmincapacity) {Modcount++; //overflow-conscious Code        if(Mincapacity-elementdata.length > 0)//if the array real storage is larger than the array capacity increasesgrow (mincapacity); }Private voidGrowintmincapacity) {        //overflow-conscious Code        intoldcapacity = Elementdata.length;//the original capacity        intNewcapacity = oldcapacity + (oldcapacity >> 1);//The new capacity is 1.5 times times the old        if(Newcapacity-mincapacity < 0)//It's a little more, just as real.Newcapacity =mincapacity; if(Newcapacity-max_array_size > 0)//if it's bigger than the biggest ,Newcapacity =hugecapacity (mincapacity); //mincapacity is usually close to size, so this is a win:Elementdata =arrays.copyof (Elementdata, newcapacity);//copy array}Private Static intHugecapacity (intmincapacity) {//Note It's a static method .        if(Mincapacity < 0)//overflow less than 0, throw exception            Throw NewOutOfMemoryError (); return(Mincapacity > Max_array_size)?//greater than Max_array_size is set to Max_value, otherwise it is max_array_sizeInteger.MAX_VALUE:MAX_ARRAY_SIZE;}

2.5. Remove method

ArrayList provides four methods for removing elements, remove (int index), remove (Object o), removerange (int fromIndex, int toindex), and RemoveAll ().

Remove (int index): Removes the element at the specified position in this list.

 PublicE Remove (intIndex) {//Delete according to subscriptRangecheck (index);//Check to see if it crossesmodcount++;//Operation increasedE OldValue = elementdata (index);//get the value of the underlying        intnummoved = size-index-1;//the data to be moved        if(nummoved > 0) system.arraycopy (elementdata, index+1, Elementdata, Index, nummoved);//move the array forwardElementdata[--size] =NULL;//let the GC work        returnOldValue;//return old value    }Private voidRangecheck (intIndex) {//check out of bounds        if(Index >=size)Throw Newindexoutofboundsexception (outofboundsmsg (index)); }PrivateString Outofboundsmsg (intIndex) {//does it feel like a lot of space this, haha        return"Index:" +index+ ", Size:" +size; } @SuppressWarnings ("Unchecked") E Elementdata (intindex) {        return(E) Elementdata[index]; }

Remove (Object o): Removes the specified element that first appears in this list if it exists.

 Public BooleanRemove (Object o) {if(O = =NULL) {//if it is null             for(intindex = 0; index < size; index++)                if(Elementdata[index] = =NULL) {//= = to compareFastremove (index); return true;//present and delete return True                }        } Else{//if it is not null             for(intindex = 0; index < size; index++)                if(O.equals (Elementdata[index])) {//equals to compareFastremove (index);//present and delete return True                    return true; }        }        return false;//does not exist return false    }Private voidFastremove (intindex) {Modcount++;//Increased number of operands        intnummoved = size-index-1;//Number of moves        if(nummoved > 0)//MovingSystem.arraycopy (Elementdata, index+1, Elementdata, Index, nummoved); elementdata[--size] =NULL;//Let GC do it work}

2.6. Get method

    Public E get (int  index) {        Rangecheck (index); // Check to see if it crosses        return elementdata (index); // fetch Value }

2.7, pay attention to sublist method

 Public Static voidMain (string[] args) {List<Integer> List1 =NewArraylist<integer>(); List1.add (1); List1.add (2); //Create a new list that contains List1 by using the constructor List2List<integer> List2 =NewArraylist<integer>(List1); //generate a List1-like list with sublist List3List<integer> list3 = list1.sublist (0, List1.size ()); //Modify List3List3.add (3);        System.out.println (List1.size ()); System.out.println ("List1 = = List2:" +list1.equals (List2)); System.out.println ("List1 = = List3:" +list1.equals (LIST3)); }

The above piece of code I feel that the big people will think the result is 2 false,list2 is a new structure is certainly not the same as the List1, List3 is certainly not the same interception. So I think it's all false, we go deep into the sublist to see.

 PublicList<e> sublist (intFromIndex,intToindex) {Sublistrangecheck (FromIndex, toindex, size);//check subscript and size        return NewSublist ( This, 0, FromIndex, toindex);//Create a new Sublist object, note that this is passed in, which represents the object to intercept .}Private classSublistextendsAbstractlist<e>Implementsrandomaccess {//I rub it, I feel like a list.Private FinalAbstractlist<e>parent;Private Final intParentoffset;Private Final intoffset;intSize//I rub, the familiar feelingSublist (abstractlist<e> Parent,intOffsetintFromIndex,intToindex) {//just the structure             This. parent = parent;//this.parent = parent, and the parent is the list passed in front, which means that this.parent is the reference to the original list.              This. Parentoffset =FromIndex;  This. Offset = offset +FromIndex;  This. Size = Toindex-FromIndex;  This. Modcount = ArrayList. Thisthe. modcount;//operand is the same as the original}

The original sublist inside operation is the original list, and did not generate a new list, resulting in 2 is actually the same.

So the correct result above is:

List1 = = List2:false
List1 = = List3:true

Iii. Summary of ArrayList

Because it is based on the implementation of the array, the main features are as follows:

1, insert, delete is slow, because insert, delete need to move data location.

2, you can insert data repeatedly, you can insert null.

3, find relatively fast, you can use the subscript directly.

Java Collection-arraylist

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.