Java Collection Class list of source Analysis (ii)

Source: Internet
Author: User
Tags array length shuffle

This section focuses on the differences between several implementation classes of the list interface:

1. Thread Safety

vectors are thread-safe, while ArrayList and LinkedList are non-thread-safe. from the source code, we know that the methods in the vector class are mostly synchronous, that is, the Synchronized keyword modification, and those that are not synchronized keyword modification by invoking other synchronization methods or using synchronous code block To achieve synchronization.

1      Public synchronized voidaddelement (E obj) {2modcount++;3Ensurecapacityhelper (Elementcount + 1);4elementdata[elementcount++] =obj;5     }6 7      Public synchronized Booleanremoveelement (Object obj) {8modcount++;9         inti =indexOf (obj);Ten         if(I >= 0) { One Removeelementat (i); A             return true; -         } -         return false; the     } -  -      Public synchronizedE Get (intindex) { -         if(Index >=elementcount) +             Throw Newarrayindexoutofboundsexception (index); -  +         returnElementdata (index); A     } at  -      Public synchronized voidInsertelementat (E obj,intindex) { -modcount++; -         if(Index >Elementcount) { -             Throw Newarrayindexoutofboundsexception (Index -+ ">" +elementcount); in         } -Ensurecapacityhelper (Elementcount + 1); toSystem.arraycopy (Elementdata, index, Elementdata, index + 1, Elementcount-index); +Elementdata[index] =obj; -elementcount++; the}
View Code
1      Public Booleancontains (Object o) {2         returnIndexOf (o, 0) >= 0;3     }4 5      Public synchronized intIndexOf (Object o,intindex) {6         if(O = =NULL) {7              for(inti = index; i < Elementcount; i++)8                 if(elementdata[i]==NULL)9                     returni;Ten}Else { One              for(inti = index; i < Elementcount; i++) A                 if(O.equals (Elementdata[i])) -                     returni; -         } the         return-1; -     } -  -      PublicEnumeration<e>elements () { +         return NewEnumeration<e>() { -             intCount = 0; +  A              Public Booleanhasmoreelements () { at                 returnCount <Elementcount; -             } -  -              PublicE nextelement () { -                 synchronized(Vector. This) { -                     if(Count <Elementcount) { in                         returnElementdata (count++); -                     } to                 } +                 Throw NewNosuchelementexception ("Vector enumeration"); -             } the         }; *}
View Code2. Applicable conditions

ArrayList: For random access more frequent (self-contained index), while insert and delete operations less;

LinkedList: Applies to insertions and deletions more frequently (modify the front and back nodes), while random access is less in the case;

Vector: Used in situations where thread safety is required (method synchronization), execution is inefficient, and data volume is high.

3. Memory consumption

In terms of memory consumption, LinkedList < ArrayList < vectors.

LinkedList is implemented in the form of a linked list, so there is no need to specify capacity size, so memory consumption is low, while ArrayList and vectors are implemented in the form of arrays, which require the size of the initial capacity (which is 10 by default) and the need to scale when capacity is insufficient. In terms of capacity expansion:

    • ArrayList only increases the current half of the array length , i.e. newcapacity = oldcapacity + (oldcapacity >> 1), the method of expanding the source code is as follows:
1     Private voidGrowintmincapacity) {2         //overflow-conscious Code3         intOldcapacity =elementdata.length;4         intNewcapacity = oldcapacity + (oldcapacity >> 1);5         if(Newcapacity-mincapacity < 0)6Newcapacity =mincapacity;7         if(Newcapacity-max_array_size > 0)8Newcapacity =hugecapacity (mincapacity);9         //mincapacity is usually close to size, so this is a win:TenElementdata =arrays.copyof (Elementdata, newcapacity); One}
View Code
    • each time the vector increments the current array length , i.e. newcapacity = oldcapacity + ((capacityincrement > 0)? capacityincrement: oldcapacity), Capacityincrement is a human-specified expansion size, the default is 0, the source code in the method of expansion is as follows:
1     Private voidGrowintmincapacity) {2         //overflow-conscious Code3         intOldcapacity =elementdata.length;4         intNewcapacity = Oldcapacity + ((capacityincrement > 0)?5 capacityincrement:oldcapacity);6         if(Newcapacity-mincapacity < 0)7Newcapacity =mincapacity;8         if(Newcapacity-max_array_size > 0)9Newcapacity =hugecapacity (mincapacity);TenElementdata =arrays.copyof (Elementdata, newcapacity); One}
View Code

In summary, vector to memory consumption is higher, followed by ArrayList.

4. Set sorting

With the data storage Method (collection), of course, considering the order of the data in the collection, the following is a simple summary of the collection order:

    • The sorting in the collection is usually implemented by invoking static methods in the collections class , commonly used in the following ways: Sort, reverse, shuffle, Min, Max, and so on.
1linkedlist<integer> LinkedList =NewLinkedlist<integer>();2Linkedlist.add (100);3Linkedlist.add (120);4Linkedlist.add (110);5Collections.sort (LinkedList);//Ascending order6 System.out.println (linkedlist);7         8Collections.sort (LinkedList,NewComparator<integer>() {9 Ten @Override One              Public intCompare (integer O1, integer o2) { A                 //TODO auto-generated Method Stub - //return 0; -                 returnO2.compareto (O1);//Descending arrangement the             } -         }); - System.out.println (linkedlist); -          +Collections.shuffle (LinkedList);//random order of Chaos - System.out.println (linkedlist); +          ACollections.reverse (LinkedList);//Reverse at System.out.println (linkedlist); -          -System.out.println (Collections.min (LinkedList));//Minimum Value -System.out.println (Collections.max (LinkedList));//Maximum Value
View Code

This gives only the sort code of LinkedList, and the sort of ArrayList and vectors is the same operation, which is not mentioned here.

Java Collection Class list of source Analysis (ii)

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.