"Java Source Analysis" Linkedhashset and HashSet source Analysis __java

Source: Internet
Author: User

Definition of Class

public class hashset<e>
extends abstractset<e>
implements Set<e>, Cloneable, java.io.serializable{}

is a subclass of Abstractset that implements the set interface and the serialization interface as well as the cloning interface. The interior is actually a HashMap instance. Do not guarantee traversal order, allow empty elements to add delete contains and size operations are constant time complexity. However, the iteration time complexity depends on the number of elements in the hashset and the capacity of the HashMap. So if the iterative performance requirements are higher, do not set the initial capacity is too large or set the load factor too small hashset is not thread-safe, in a multithreaded environment, the need to use object locks to synchronize or using set S = Collections.synchronizedset (New HashSet (...)); When you create a wrapper for a thread-safe class using an iterator for iterative access, if you modify the hashset structure, there will be a fail-fast phenomenon, which is thrown concurrentmodificationexception exception.

Primary member variable

Static final Long serialversionuid = -5024744406713321676l;

private transient hashmap<e,object> map;

Dummy value to associate with a Object in the backing Map
private static final Object PRESENT = new Object ();

One is the ID used to serialize, one is the hashset of the HashMap implementation which is essentially used, and the other member variable is somewhat special. because the set type is not allowed to have duplicate elements, and HashSet is implemented with HashMap, HashMap is not allowed to have duplicate key. So will deposit in HashSet entity as key, deposit a value can guarantee HashSet object uniqueness , this empty as the value of the object is here present

Constructors

1 public
HashSet () {
    map = new hashmap<> ();///default capacity 16 load factor 0.75
}

//2 public
HashSet ( collection<? Extends e> c) {
    map = new Hashmap<> (Math.max ((int) (C.size ()/.75f) + 1));
    AddAll (c);
}

3 public
hashset (int initialcapacity, float loadfactor) {
    map = new Hashmap<> (initialcapacity, loadfactor);
}

4 public
hashset (int initialcapacity) {
    map = new hashmap<> (initialcapacity);
}

5
//Constructs a new, empty linked hash set.  (This package private constructor are only used by Linkedhashset.)
HashSet (int initialcapacity, float loadfactor, Boolean dummy) {
    map = new Linkedhashmap<> (initialcapacity, loadfactor);
}

The first four constructors are relatively simple and intuitive, focusing on the fifth one, which is the construction method of its subclass Linkedhashset, and its internal implementation is also a HashMap subclass Linkedhashmap

Principal Member Methods

Because the internal implementation is a hashmap, so hashset some of the main operations are through the HASHMAP to achieve

Public boolean Add (E. e) {return
    map.put (E, PRESENT) ==null;
}

public boolean remove (Object o) {return
    map.remove (o) ==present;
}

For example, add and delete here, the direct use is the HashMap method. Notice the meaning of the return null when adding: If the key is already in the hashmap when it is added, then the present is returned and the add operation returns false and the addition fails. This ensures that only elements that are not duplicated can be added. Similarly, in the deletion operation because HashMap key is the object in set, and value is the same present, so delete time if successful, then will definitely return present

Cloning operations

Public Object Clone () {
    try {
        hashset<e> newset = (hashset<e>) super.clone ();
        Newset.map = (hashmap<e, object>) Map.clone ();
        return newset;
    } catch (Clonenotsupportedexception e) {
        throw new Internalerror ();
    }
}

This method returns a copy of the current set, noting that only a copy of the set , and that the elements in the set are not copied , is what is done here is a shallow copy

Serialization and deserialization

private void WriteObject (Java.io.ObjectOutputStream s) throws java.io.IOException {//Write out of any hidden serial

    Ization Magic S.defaultwriteobject ();
    Write out HASHMAP capacity and load factor S.writeint (Map.capacity ());

    S.writefloat (Map.loadfactor ());

    Write out Size S.writeint (Map.size ());
    Write out all elements in the proper order.
For (e E:map.keyset ()) S.writeobject (e); } private void ReadObject (Java.io.ObjectInputStream s) throws Java.io.IOException, ClassNotFoundException {/Re

    Ad in any hidden serialization magic s.defaultreadobject ();
    Read in HASHMAP capacity and load factor and create backing HashMap int capacity = S.readint ();
    float loadfactor = S.readfloat ();
           Map = ((hashset) this) instanceof Linkedhashset?

    New linkedhashmap<e,object> (capacity, Loadfactor): New hashmap<e,object> (capacity, loadfactor)); Read in size int size = S.reaDInt ();
    Read in the ' all elements ' proper order.
        for (int i=0; i<size; i++) {e E = (e) s.readobject ();
    Map.put (E, PRESENT);
 }
}

Serialization and deserialization also need to be aware that the write and read order of the data must be consistent

Linked Source Analysis

Before looking at HashSet's source code, the fifth constructor has explained how to build a linkedhashset. In fact, similar to Linkedhashmap, Linkedhashset also added a two-way linked list to preserve the order of objects on the basis of the original data. However, Linkedhashmap is designed to support access order and Insertion order settings (which are often used to implement LRU functionality when configured in the order of access), while Linkedhashset is not supported.

Definition of Class

public class linkedhashset<e>
extends hashset<e>
implements Set<e>, Cloneable, java.io.Serializable {}

Is the subclass of the hashset, the implementation of the interface and HashSet different, where the implementation of the set interface. Serialization and cloning operations are also supported. The biggest feature relative to Hashset,linkedhashset is that the traversal order is predictable (consistent with the insertion order), because a two-way list is added to the HashSet, which maintains the insertion Order of the entities (repeated inserts do not affect the original order). This set of doubly linked lists is useful in maintaining the order of elements Linkedhashset provides all the methods of the Set class and allows for empty elements , and the Add-remove contains operations often count time complexity due to the need to maintain a two-way list , so it's just a little bit more performance than HashSet. The two factors that affect efficiency are also capacity and loadfractor. It is not thread-safe , so when you need to synchronize or wrap an iterator in a multithreaded environment, the behavior of modifying the Linkedhashset structure appears fail-fast

Constructors

1 public
linkedhashset (int initialcapacity, float loadfactor) {
    super (initialcapacity, Loadfactor, true);
}

//2 public
linkedhashset (int initialcapacity) {
    super (initialcapacity,. 75f, True);
}

3 public
Linkedhashset () {
    super (. 75f, True);
}

4 Public
Linkedhashset (collection< extends e> c) {
    Super Math.max (2*c.size (), one),. 75f, True);
    AddAll (c);
}

Note the third parameter of the first constructor, which can directly view the source of the Linkedhashmap. If this argument is true, the order of the doubly linked lists is arranged in the order of access, if False, or by default, in the order of insertion.

Linkedhashset implementation is very simple, only constructors, mainly because the specific implementation code and the parent class exactly the same, are implemented in the HashSet class. and the constructor is all a constructor that calls three parameters of super () This method is also listed above, that is, the new one Linkedhashmap, and the third parameter is set to True, maintaining the bidirectional list in the order of access

HashSet (int initialcapacity, float loadfactor, Boolean dummy) {
    map = new Linkedhashmap<> (initialcapacity, loadfactor);
}

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.