Summary: Java Collection advanced explaining 1

Source: Internet
Author: User
Tags set set

Set advanced 1---Specify the initial capacity for the collection

Collections are very widely used in Java programming, and when the amount of containers becomes very large, the initial capacity is important.

Because of the expansion of the need to consume a lot of manpower and material resources.

In the same vein, the initial capacity of collection is also very important. So: For a known scenario, specify the initial capacity for the collection.

Importjava.util.ArrayList;Importjava.util.List; Public classColtest { Public Static voidMain (string[] args) {Base_user Baseuser=NULL; LongBegin1 =System.currenttimemillis (); List<Base_User> List1 =NewArraylist<base_user>();  for(inti = 0; i < 1000000; i++) {Baseuser=NewBase_user (i, "chenssy_" +i,i);          List1.add (Baseuser); }          LongEnd1 =System.currenttimemillis (); System.out.println ("List1 Time:" + (End1-begin1)); LongBegin2 =System.currenttimemillis (); List<Base_User> List2 =NewArraylist<> (1000000);  for(inti = 0; i < 1000000; i++) {Baseuser=NewBase_user (i, "chenssy_" +i,i);          List2.add (Baseuser); }          LongEnd2 =System.currenttimemillis (); System.out.println ("List2 Time:" + (End2-begin2)); }      }

Analysis:

Inserting 1 million data, List1 did not request initialization capacity, while list2 initialized capacity 1000000. Running results we can see that the list2 speed is about twice times the List1.

The expansion mechanism of ArrayList is a relatively consuming resource. Let's look at ArrayList's Add method first:

 Public BooleanAdd (e e) {ensurecapacity (size+ 1); Elementdata[size++] =e; return true; }               Public voidEnsurecapacity (intmincapacity) {Modcount++;//Modifying Counters        intOldcapacity =elementdata.length; //The current required length exceeds the length of the array and is expanded to handle        if(Mincapacity >oldcapacity) {Object olddata[]=Elementdata; //New capacity = old capacity * 1.5 + 1            intNewcapacity = (oldcapacity * 3)/2 + 1; if(Newcapacity <mincapacity) newcapacity=mincapacity; //array copy, generating a new arrayElementdata =arrays.copyof (Elementdata, newcapacity); }        }      

ArrayList each time a new element is added, it will detect whether the current capacity of ArrayList has reached the critical point, and if it reaches the critical point, it will expand 1.5 times times.

However, the expansion of ArrayList and the creation of a new array of copies of the array are quite resource-intensive.

On the premise of large data volume, it is more advantageous to specify the capacity of initialization, the improvement of efficiency and the utilization of resources.

Set advanced 2---Traverse map set kv using EntrySet

There are two common methods for HASHMAP traversal, which is to use keyset and entryset to traverse

But the traverse speed of the two is different.

The first type: EntrySet high efficiency
New= while (Iter.hasnext ()) {     = (map.entry) Iter.next ();      = Entry.getkey ();      =

Second: low efficiency of keySet
New= while (Iter.hasnext ()) {     = iter.next ();      =

For keyset is actually traversed 2 times, one is converted to iterator, one time from the HashMap to remove the value of key.

And EntrySet just traversed the first time, he put the key and value in the entry, so soon.

Set advanced 3---the stability and order of rational use of set

Reasonable use of the stability (order) and order of the set (sort), to avoid the disorder of the set and instability caused by the negative effects.

    • Stability refers to the sequence of elements that each traversal of a set is certain.
    • The order is the result of the traversal is sorted by some comparison rule in sequence.

ArrayList is Order/unsort,hashmap is Unorder/unsort,treeset is Order/sort, you can also sort the results by TreeSet combining ArrayList.

Some characteristics of common Java collections:
    • ①, LinkedList Bottom is doubly linked list. ArrayList: The bottom of the array structure, the elements added in order can be repeated.

    • ②, HashSet: The bottom of the hash table algorithm, the elements added inside the unordered is not repeatable.

    • ③, HashMap: The bottom is also using a hash table algorithm, but the elements added inside is the form of key-value. Key does not allow duplicates, value can.

How to make good use of the principles of these sets, simplifying our programming.

1. Count the occurrences of each character in a string?

Parse: Given a string of strings, count the occurrences of each character. Statistical characters are not duplicated, and the number of occurrences we can do without the tube. So it's easy to think of the set principle of Map, Key-value. It is a good way to implement the statistical characters in Map<character,integer>.

HashMap
ImportJava.util.HashMap;ImportJava.util.Map; Public classCntest { Public StaticMap<character, integer> Countchar (Map<character, integer>map,string str) {            //resolves the given string to an array constructed of a single character            Char[] chars =Str.tochararray ();  for(Charc:chars) {                if(Map.containskey (c)) {intOldcount =Map.get (c); Map.put (c, Oldcount+1); }Else{map.put (c,1); }            }                         returnmap; }              Public Static voidMain (string[] args) {String str= "Hello World"; //defines a Map collection that holds statistics for the character--numberMap<character, integer> HashMap =NewHashmap<character, integer>();            System.out.println (Countchar (HASHMAP,STR)); //{w=1, d=1, =1, e=1, R=1, o=2, l=3, h=1}        }}

Add: Here we use to save the statistical character is the HashMap implementation class, where the printed character statistics are unordered.

Linkedhashmap

According to the order of the string given by the ordered statistics out

          Public Static void Main (string[] args) {            = "Hello World";             // defines a Map collection that holds statistics for the     character--number            New Linkedhashmap<character, integer>();            System.out.println (Countchar (LINKEDHASHMAP,STR));             // {h=1, e=1, l=3, o=2,  =1, W=1, R=1, d=1}         }

TreeMap

Prints the given string in UICode encoding order

      Public Static void Main (string[] args) {            = "Hello World";             // defines a Map collection that holds statistics for the     character--number            New Treemap<character, integer>();            System.out.println (Countchar (TREEMAP,STR));             // {=1, d=1, e=1, H=1, l=3, o=2, R=1, w=1}     }

Second, remove the duplicate data for the given array?

Parse: Put the elements in the array into set, then transform the set set to an array.

ImportJava.util.HashSet;ImportJava.util.Set; Public classCrtest { Public StaticInteger[] Clearrepeat (int[] Array) {Set<Integer> set =NewHashset<integer>();  for(intI:array)        {Set.add (i); } integer[] NewArray= Set.toarray (Newinteger[set.size ()]); returnNewArray; }               Public Static voidMain (string[] args) {//To create an array, you can see that 2 and 4 are duplicates.        int[] Array = {1,2,3,4,2,2,3,4}; Integer[] NewArray=clearrepeat (array);  for(Integer i:newarray) {System.out.println (i); }        //1 2 3 4             }}

In the same way we can change the implementation class of set set, HashSet is unordered, we can use * * linkedhashset** to ensure the established order; TreeSet ensure natural order

Over

By: a Amumu

Summary: Java Collection advanced explaining 1

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.