The object of JAVA holding--a probe into containers

Source: Internet
Author: User

Introduction

If a program contains only a fixed number of objects whose life cycle is known, then this is a very simple program--"Think in Java"

Before you know the container, ask a question, ArrayList and LinkedList who's processing faster?


A way to hold an object

In Java, we can use arrays to hold a set of objects. However, arrays are fixed size, and in general, we do not know how many objects will be required when we write the program, so the fixed size of the array is somewhat limited for programming.

The Java class Library provides a fairly complete set of container classes to solve this problem, where the basic types are list,queue,set,map, which are called collection classes. However, the Java class Library uses collection to refer to the subset {List,queue,set} in the collection class, so the collection class is also known as a container. Containers provide a perfect way to save objects.


Two types of safe containers

Java uses generics to ensure that we do not insert an incorrect type into a container, but that Java generics exist only in the source code of the program, and the type is erased when compiled by the compiler. To give an example:

Pre-compiled list<string> list = new arraylist<> (); List.add ("OK"); System.out.println (list.get (0));//After compiling list list = new ArrayList () list.add ("OK"); System.out.println (String) list.get (0));

The advantage of this is that when you write a program, objects of other non-exported types are not added to the container.


Three List

The reason the array stores multiple objects is because it declares in advance how many objects can be stored. How does the container implement the storage of the indefinite number of objects?

ArrayList part source private static final int default_capacity = 10;private  static final object[] empty_elementdata = {};p rivate transient object[]  elementdata;private int size;public arraylist (int initialcapacity)  {     super ();    if  (initialcapacity < 0)          throw new illegalargumentexception ("illegal capacity: " +                                              initialcapacity);     this.elementdata =  new object[initialcapacity];} Public arraylist ()  {    super ();     this.elementdata&nbsP;= empty_elementdata;} Public boolean add (e e)  {    ensurecapacityinternal (size + 1 );   // increments modcount!!     elementdata[size++] = e;    return true;} Private void ensurecapacityinternal (int mincapacity)  {    if  ( Elementdata == empty_elementdata)  {        mincapacity  = math.max (default_capacity, mincapacity);    }     Ensureexplicitcapacity (mincapacity);} Private void ensureexplicitcapacity (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, so this is  a win:    elementdata = arrays.copyof (elementData, newCapacity);}

As we can see, there is a elementdata array in the ArrayList class. When using the parameterless constructor, the array length defaults to NULL, and when the object is joined to ArrayList, a method is called to determine whether the array can drop the object. When the array is empty, set the array length to 10 and request the appropriate size space, and when the array is full, re-apply at least 1.5 times times the size of the original array (unless the maximum value of INT-8) is reached. In LinkedList, it is not used in this way, but in the form of a linked list.

LinkedList Add method void Linklast (E e) {final node<e> L = last;    Final node<e> NewNode = new node<> (l, E, NULL);    last = NewNode;    if (L = = null) first = NewNode;    else L.next = NewNode;    size++; modcount++;}

In LinkedList, his Add method invokes the Linklast method, adding a new node directly behind the list.


Four Set

The set type does not save duplicate elements. The Equals method is used to determine whether an object element is equal, so when you save a custom object, overriding the Equals method depends on the mutable attribute, which can cause some problems.


Five Map

The map type is a container that can map objects to other objects, with a Get method that differs from the list. The HashSet class contains a HashMap object, and the implementation of HashSet relies on HashMap.

The implementation of HashMap takes the form of an array of linked lists, where each position of the array is stored as a chain header. The lookup will first find the corresponding array subscript by the hash of key, and then find the corresponding object in the linked list of the array subscript, and find the Equals method.


Six Queue

The queue is a typical FIFO container, and LinkedList implements the queue interface. The Priorityqueue implements the priority queue.


The choice of seven lists

At the beginning of the article raised a question, the array implementation of the list is fast or the list of lists implemented by fast. Simulate a test:

Public static void add () {    long start = 0;     long end = 0;    list<integer> alist = new  ArrayList<> ();    list<integer> llist = new  Linkedlist<> ();     system.out.println ("ArrayList the number of milliseconds required to add 10 million data");     start = system.currenttimemillis ();    for  (int i=0; i< 10000000; i++)     {        alist.add (i);     }    end = system.currenttimemillis ();     system.out.println (End-start);     system.out.println ("The number of milliseconds required to add 10 million data to LinkedList");     start = system.currenttimemillis ();    for  (int  i=0; i<10000000; i++)     {        llist.add (i);     }    end = system.currenttimemillis ();     System.out.println (end-start+ "\ n");     system.out.println ("The number of milliseconds to delete data from the 10 million data ArrayList");     start = system.currenttimemillis ();     alist.remove (0);     alist.remove (2000000);     alist.remove (4000000);     alist.remove (6000000);     alist.remove (8000000);     alist.remove (9999994);     end = system.currenttimemillis ();     System.out.println (End - start);     system.out.println (" LinkedList the number of milliseconds required to delete data from 10 million data ");     start = system.currenttimemillis ();     llist.remove (0); &NBSP;&NBSP;&NBSP;&NBSP;LLIST.REmove (2000000);     llist.remove (4000000);     llist.remove (6000000);     llist.remove (8000000);     llist.remove (9999994);     end = system.currenttimemillis ();     system.out.println (end -  Start+ "\ n");     system.out.println ("ArrayList the number of milliseconds to find data from 10 million data");     Start = system.currenttimemillis ();     alist.contains (0);     alist.contains (2000000);     alist.contains (4000000);     Alist.contains (6000000);     alist.contains (8000000);     alist.contains (10000000);     end = system.currenttimemillis ();     System.out.println (End - start);     system.out.println (" LinkedList the number of milliseconds required to find data from 10 million data "); &NBSP;&NBSP;&NBSP;&NBSP;START&NBsp;= system.currenttimemillis ();     llist.contains (0);     Llist.contains (2000000);     llist.contains (4000000);     llist.contains (6000000);     llist.contains (8000000);     llist.contains (10000000);     end = system.currenttimemillis ();     system.out.println ( End - start+ "\ n");}

As you can see, the list of array implementations is faster than the linked list, regardless of the circumstances. When I set the initial size of the array to 10 million in the ArrayList constructor method, the ArrayList adds data slowly and drops to about 5000 milliseconds, so the general situation does not need to be optimized.


Summarize

Simple Container class Diagram:

The Java container is divided into two categories, one is collection, and the other is map. collection contains three types of collections: Set,list,queue.

If you want the data in the set to be orderly, use TreeSet.

Hashtable and vectors are thread-safe, but are not recommended, use the container under the Java.util.concurrent package.

HashMap allows the key/value value to be null.

The object of JAVA holding--a probe into containers

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.