A few thoughts on the test of HashMap in Java

Source: Internet
Author: User
Tags shallow copy

0. Preface

Work busy, a long time without looking at the algorithm, even the DFA sensitive word algorithm to be optimistic for a while to understand ... is really and third-order Rubik's Cube reduction, the pastoral will be Wu, very pity ah.

In the DFA algorithm, the first step is to understand its data structure, on this basis, it involves some hashmap assignment. The assignment here is very interesting, with three hashmap tossing and turning assignments, which solves the initialization of the sensitive vocabulary.

All of which belong to the HashMap "shallow copy" below, so what is the copy method of HashMap in Java?

1. Test code
HashMap Hm_source =NewHashMap (); HashMap Hm_clone=NewHashMap (); Hm_source.put ("1", "1"); //HashMap Deep Clone Method 1Hm_clone =(HASHMAP) Hm_source.clone ();//HashMap Deep Clone Method 2Hm_clone.putall (Hm_source);//HashMap Shadow Clone//hm_b = hm_a;Hm_source.put ("2", "2"); System.out.println ("Hm_source added element, Hm_source:" +Hm_source); System.out.println ("Hm_source added element, Hm_clone:" +Hm_clone); System.out.println ("Point to the same memory address:" + (hm_source==hm_clone)); System.out.println ("Whether the first element points to the same memory address:" + (Hm_source.get (1) ==hm_clone.get (1)));

The above describes two methods of HashMap deep copy, namely Hashmap.clone () and Hashmap.putall (Hm_source), the output is as follows:

Hm_source add element, Hm_source:{1=1, 2=2}hm_source add element, hm_clone:{1=1} points to the same memory address:false  Whether the first element points to the same memory address:true

What about a shallow copy? (the part of the comment in the code, the direct equals sign = Assignment), the output is as follows:

Hm_source add element, Hm_source:{1=1, 2=2}hm_source add element, hm_clone:{1=1, 2=2} points to the same memory address:true whether the first element points to the same memory address: true
2. Output parsing

It is not difficult to find that the depth of the copy is indeed its name,

deep copy: two HashMap objects do not seem to be completely unrelated, adding each other to modify the elements, will not affect each other;

Shallow copy: two HashMap objects are "soft link ln", each other, you change, I also change.

3. Is the above conjecture correct?

Our party's ideological line is seeking truth from facts, the analysis of the fundamental differences, we can look at the JDK clone function source code.

But some of the preliminary conclusions we get from the phenomenon are:

    1. A shallow copy of the two objects using the same memory address, the deep copy of the object address "another portal";
    2. A deep copy of the two objects is not completely "irrelevant", just copy the elements of the reference;

As for conclusion 3.2, I also learned in HashMap's Clone method blog post that the HashMap element used is the bean type, the element modification under the deep copy, and the "broken bones attached to the tendon" to allow two HashMap to be updated simultaneously.

However, only "element modification", if "element additions and deletions", the two HashMap objects are "over face not", will not synchronize updates.

4, Hashmap.clone ()

JDK is a rare learning material, the source is still to read. Now also paste over, do some records.

/*** Returns A shallow copy of this <tt>HashMap</tt> instance:the keys and * values themselves is     Not cloned. * "Our Chinese is called" deep copy ", the foreigner beauty its name Yue" Copy an instance of the ' shallow copy ', more rigorous "*@returna shallow copy of this map*/@SuppressWarnings ("Unchecked") @Override PublicObject Clone () {HashMap<K,V>result; Try{result= (hashmap<k,v>)Super. Clone (); } Catch(clonenotsupportedexception e) {//This shouldn ' t happen, since we is cloneable            Throw NewInternalerror (e);        } result.reinitialize (); Result.putmapentries ( This,false); returnresult; }
/*** Implements Map.putall and Map constructor * *@paramm The map *@paramevict False when initially constructing the this map, else * True (relayed to method Afternodeinsertion). */    Final voidPutmapentries (map<?extendsK?extendsV> m,Booleanevict) {        ints =m.size (); if(S > 0) {            if(Table = =NULL) {//pre-size                floatFT = ((float) s/loadfactor) + 1.0F; intt = ((ft < (float) maximum_capacity)?                         (int) ft:maximum_capacity); if(T >threshold) Threshold=tablesizefor (t); }            Else if(S >threshold) resize ();  for(MAP.ENTRY&LT;?extendsK?extendsV>E:m.entryset ()) {K key=E.getkey (); V value=E.getvalue ();//"Putval method inside I first sweep, also did not involve HashMap instance object's new, is some HASHMAP structure node's new"Putval (hash (key), key, value,false, evict); }        }    }

The final interpretation of the code is owned by jdk1.8.x.

A few thoughts on the test of HashMap in Java

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.