Detailed parsing of Java containers

Source: Internet
Author: User
Tags addall array length

Preface: In Java Development We certainly will use a lot of collections, here I will summarize the common collection class, each collection class advantages and disadvantages, so that we can better use the collection. Now I'm going to use a picture to show

Where the light green represents the interface, the red color represents the class that we often use.

1: Basic Concept

The purpose of the Java Container Class library is to save the object, which can be divided into 2 concepts.

1.1:collection

A sequence of independent elements that obey one or more rules. Where list must save elements in the order in which they are inserted, set cannot have duplicate elements, and queue determines the order in which the objects are produced (usually the same as the insertion Order)

1.2:map

A pair of value-key pairs of objects that allow keys to look up values. ArrayList allows us to use numbers to look up values, which are associated with numbers and objects. And map allows us to use an object to find an object, which is also known as an associative array. Or it's called a dictionary.

2:list

The list promises to maintain elements in a particular sequence. The list interface adds a number of methods to the collection, allowing you to insert and remove elements in the middle of a list. The following are mainly about 2 kinds of list

2.1: The basic ArrayList

The advantage of this is that random access to elements is fast, but the insertion and removal in the middle is relatively slow

So now let's see why ArrayList random access is fast, and insertion removal is slow. First, the initialization of ArrayList.

There are three ways to initialize the ArrayList as follows

Private transient object[] elementdata;
Public ArrayList () {this        ];    }  Public ArrayList (int initialcapacity) {        super ();        if (initialcapacity < 0)            throw new IllegalArgumentException ("Illegal capacity:" +                                               initialcapacity);        This.elementdata = new object[initialcapacity];    } Public ArrayList (collection<? extends e> c) {        elementdata = C.toarray ();        size = Elementdata.length;        C.toarray might (incorrectly) not return object[] (see 6260652)        if (Elementdata.getclass ()! = Object[].class) 
   elementdata = arrays.copyof (elementdata, size, object[].class);    }

We can see that ArrayList is actually using an array (the default is an array of length 10). All ArrayList have the same efficiency as the array when reading, and its time complexity is 1.

Insert the tail is elementdata[size++] = e; Of course, the middle will be expanding. Now it is mainly said that the insertion of the middle why relatively slow source as follows

public void Add (int index, E element) {        Rangecheckforadd (index);//validation (can not be considered)        ensurecapacityinternal (size + 1); c3/>//increments modcount!! (Expansion beyond the current array length)        system.arraycopy (elementdata, index, Elementdata, index + 1,                         size-index);(core code)        Elementdata[index] = element;        size++;    }

System.arraycopy (Elementdata, index, Elementdata, index + 1) The first parameter is the source array, the source array starting position, the target array, the destination array starting position, and the number of array elements copied. So this means to move one bit backwards from index to the index, and finally to empty it and assign the element to it. So we don't know which position to insert, so we'll make a match then it will have a time assignment of N.

2.2:linkedlist

It is inserted and removed in the middle of the list at a lower cost, providing an optimized sequential access, but relatively slowly in terms of random access. But his features are much more powerful than ArrayList. Support for queue and stack

The listedlist uses chained storage. Chained storage will set a node. Includes three-part precursor nodes, successor nodes, and data values. So when storage is stored, his physical address is not necessarily contiguous.

Let's take a look at its middle insert implementation

From the code we can see that we first get the precursor node of the inserted index element, and then take this element as the successor node, and then create a new node, and the new node precursor node and the acquiring precursor node are the same, and the second node is equal to the element to be moved. Therefore, there is no need to loop, so the efficiency is higher when inserting and deleting.

We're looking at the query (we can figure out that it's a lot less efficient than ArrayList)

3:set

Set is also a collection, but his feature is not to have duplicate objects, so set is most commonly used to test the attribution, it is easy to ask whether an object exists in the set. and set is the same interface with collection, no additional functions, just behave differently.

3.1:hashset

HashSet query speed is faster, but the stored elements are random and not sorted, below I write a program to see

public static void Main (string[] args) {        /**         * is not sequential, because HashSet is hashed (at speed)         */        Random random=new Random (+);        Set<integer> intset=new hashset<integer> ();        for (int i=0;i<10000;i++) {            intset.add (random.nextint);        }        System.out.print (Intset);    }

3.2:treeset

TreeSet is to store elements in the red-black tree structure, so the stored results are sequential (so if you want to store your own collection in order then choose TreeSet)

public static void Main (string[] args) {        random random=new random (n);        Set<integer> intset=new treeset<integer> ();        for (int i=0;i<10000;i++) {            intset.add (random.nextint);        }        System.out.print (Intset);    }

About Linkedhashset back again.

4:queue

The queue is a queue, which is typically a first-in-one-out container, where elements are placed from one end of the container, removed from the other, and the order in which the elements are placed in the container is the same as the order in which they are fetched. LinkedList provides the implementation of the queue, LinkedList up to the queue. Where queue has offer, peek, element, pool, remove and other methods

An offer is to insert an element into the tail of the queue and return false to indicate that the add failed. Both peek and element will return to the head without removing it, but peek returns NULL when the header is null, and element throws a Nosuchelementexception exception. The poll and remove methods are removed and returned to the head, but poll is null in the queue and remove throws the Nosuchelementexception exception, the following is an example

  public static void Main (string[] args) {        queue<integer> queue=new linkedlist<integer> ();        Random rand=new random ();        for (int i=0;i<10;i++) {            queue.offer (Rand.nextint (i+10));        }        PRINTQ (queue);        Queue<character> qc=new linkedlist<character> ();        for (char c: "HelloWorld". ToCharArray ()) {            qc.offer (c);        }        System.out.println (Qc.peek ());        PRINTQ (QC);        List<string> mystrings=new linkedlist<string> ();        Mystrings.add ("1");        Mystrings.get (0);        Set<string> a=new hashset<string> ();        Set<string> set=new hashset<string> ();        Set.add ("1");    }    public static void Printq (queue queue) {while        (Queue.peek

From the results of the above output we can see that the result is not a sequential, no rules, this time if you want the queue to follow the rule output then we have to consider the priority, this time we should use Priorityqueue, At this point, if the call to the Offer method inserts an object, the object will be sorted by priority in the column, the default is natural sort, of course, we can modify the order by comparator (in the next article). Priorityqueue can ensure that when you call the Peek, pool, and remove methods, the element that gets is the highest priority element in the column. Ok let's check again through the code

public static void Main (string[] args) {        priorityqueue<integer> priorityqueue = new priorityqueue<integer& gt; ();        Random rand = new Random ();        for (int i = 0; i < i++) {            Priorityqueue.offer (rand.nextint (i +));        }        QUEUEDEMO.PRINTQ (priorityqueue);        list<integer>ints= arrays.aslist (25,22,20,18,14,9,3,1,1,2,3,9,14,18,21,23,25);        Priorityqueue=new priorityqueue<integer> (ints);        QUEUEDEMO.PRINTQ (Priorityqueue);    }

As you can see from the output, the repetition is allowed, the minimum value has the highest priority (if it is a string, the space can also be counted as a value, and has a higher priority than the letter) if you want to eliminate duplication, you can store it with set and set it as the initial value of the Priorityqueue object.

5:map

Map in the actual development of the use of a very wide, especially hashmap, imagine we want to save the value of some elements of an object, if we are creating an object is a bit troublesome, this time we can use the map, HashMap is a hash function, so the efficiency of the query is relatively high, If we need an orderly we can consider using TreeMap. Here is the main introduction of the method of HashMap, we note that the HashMap key can be null, and the key value can not be repeated, if repeated after the first key value to be overwritten.

Put to add the value of the key pair, ContainsKey verify the existence of the main, Containsvalue verify that the value exists, keyset get all the key collection, values get all the value collection, EntrySet get the key value pair.

 public static void Main (string[] args) {//map<string,string> pets=new hashmap<string, string> ();        Map<string,string> pets=new treemap<string, string> ();        Pets.put ("1", "Zhang San");        Pets.put ("2", "John Doe");        Pets.put ("3", "Harry");        if (Pets.containskey ("1")) {System.out.println ("already exists key 1");        } if (Pets.containsvalue ("Zhang San")) {System.out.println ("Existing value Zhang San");        } set<string> Sets=pets.keyset ();        Set<map.entry<string, string>> entryset= pets.entryset ();        Collection<string> values= pets.values ();       for (String value:values) {System.out.println (value+ ";");}        for (String key:sets) {System.out.print (key+ ";");}            for (Map.entry entry:entryset) {System.out.println ("key:" +entry.getkey ());        System.out.println ("Value:" +entry.getvalue ()); }    }

6:iterator and foreach

The foreach syntax now works primarily on arrays, but he can also apply to all collection objects. Collection is able to use foreach because it inherits the iterator interface. Here I write a code for everyone to see

public class Iteratorclass {public    iterator<string> Iterator () {      return new Itr ();    Private class ITR implements iterator<string>{        protected string[] words= ("Hello Java"). Split ("");        private int index=0;        public Boolean Hasnext () {            return index<words.length;        }        Public String Next () {            return words[index++];        }        public void Remove () {        }}    }
Iterator iterators=new Iteratorclass (). Iterator ();        For (Iterator It=iterator;iterators.hasnext ();) {            System.out.println (Iterators.next ());        }        while (Iterators.hasnext ()) {            System.out.println (Iterators.next ());        }

From this we can see that the Foreach loop is eventually converted to a for (Iterator it=iterator;iterators.hasnext ();) except that the JDK hides us from the view. We are here to analyze an issue about list deletion. Most of us must have used a for loop or a foreach loop to delete, but the result is obviously an error, so now let's analyze why there is an error.

1: Delete with For loop (Error parsing)

2:foreach Loop Delete (Error analysis)

From the above we know that foreach will eventually turn into iterator, so it will first get the element through next, we look at the code

See for loop delete that piece of code, did not delete once Modcount will + +, so the second time at the time of deletion modcount because of increase and expectedmodcount, cannot get the element also cannot delete.

3: The correct way to delete

Use the iterator code as follows

Iterator<string> iterator=userlist.iterator ();        while (Iterator.hasnext ()) {            iterator.next ();            Iterator.remove ();        }

Please remember to add iterator.next (); This is because there is a lastred in the source code, through it to record whether it is the last element, if not add Iterator.next () so lastred=-1, the deletion of the verification of the time there is such a code if ( Lastret < 0) throw new illegalstateexception (); So it throws an exception.

7:collections and Arrays

Only 2 commonly used collections.addall and arrays.aslist are introduced here.

AddAll:

The aslist uses an array

can be seen eventually converted into ArrayList.

8: summary

1): Array is the number and object, it holds the explicit object, query the object when the query results do not need to convert, it can be multidimensional, can save the basic type of data, but once the array is generated, its capacity can not be changed. So arrays are not allowed to delete and add elements directly.

2): Collection save a single element, and map saves the associated value key pair, with Java generics, you can specify the container to hold the object type, do not put the wrong type of object in the container, take the element time does not need to transform. and collection and map can automatically adjust their size. The container may not hold the base type.

3): Like an array, list also establishes the association of the number with the object, so that arrays and lists are well-ordered containers, and list can be automatically enlarged

4): If you need a lot of random access to use ArrayList, if you want to frequently insert and delete from the middle to use LinkedList.

5): Various queue and stack supported by LinkedList

6): Map is a design that associates an object, not a number, with an object. HashMap is used for quick access, TreeMap hold keys are always in the sorted state, so it's not as fast as hashmap, and Linkedhashmap keeps elements in the order of insertion, but also provides quick access by hashing

7): Set does not accept duplicate elements, HashSet provides the fastest access, TreeSet preserves element sort state, Linkedhashset saves elements in order of insertion.

Detailed parsing of Java 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.