Java Collection Learning (16) HashSet Detailed introduction (source analysis) and usage examples

Source: Internet
Author: User
Tags constructor contains final int size object object

In this chapter, we learn about HashSet.
We first have a general understanding of HashSet, and then learn its source, and finally through the example to learn to use HashSet.

The 1th part HashSet introduction

HashSet Introduction

HashSet is a collection that has no repeating elements.
It is implemented by HashMap, does not guarantee the order of elements, and hashset allows null elements to be used.
HashSet is not synchronized. If more than one thread accesses a hash set at the same time, and at least one of the threads modifies the set, it must maintain an external synchronization. This is usually done by performing a synchronous operation on the object that naturally encapsulates the set. If no such object exists, you should use the Collections.synchronizedset method to "wrap" the set. It is a good idea to do this at creation time to prevent unexpected, different steps to access the set:

Set s = collections.synchronizedset (new HashSet (...));

HashSet the iterator returned through the iterator () is fail-fast.

The inheritance relationship of the hashset is as follows:

Java.lang.Object
        java.util.abstractcollection<e>
              java.util.abstractset<e>
                    Java.util.hashset<e> public
     
class hashset<e>
    extends abstractset<e>
    implements Set <e>, cloneable, java.io.Serializable {}

HashSet and map relate to the following diagram:

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

Constructor for HashSet

Default constructor public
hashset () 
     
///Collection Constructors public
hashset (collection<? extends e> c) 
     
// Constructors that specify hashset initial capacity and load factor public
hashset (int initialcapacity, float loadfactor) 
     
//Specify HashSet initial capacity constructors
The public hashset (int initialcapacity) 
     
//Specifies the constructor of the HashSet initial capacity and load factor, dummy does not have any effect
hashset (int initialcapacity, Float Loadfactor, Boolean dummy)

HashSet's main API

Boolean         Add (E object)
void Clear            ()
object          Clone ()
Boolean         contains Object)
Boolean         isempty ()
iterator<e>     iterator ()
boolean         Remove (object object)
int             size ()

2nd part HashSet Source Analysis

To get a better idea of the hashset principle, the following is an analysis of the HashSet source code.

Package java.util; public class Hashset<e> extends abstractset<e> implements Set<e>, Cloneable, Java.io.Serializabl
     
    e {static final long serialversionuid = -5024744406713321676l;
     
    HashSet is a private transient hashmap<e,object> map that saves content through a map (HashMap object); 
    Present is the value that inserts the key-value corresponding to the map//Because the key is needed in the HashSet, and HashMap is the Key-value key value pair;//So, when you add a key value pair to the map, the value of the key value pair is fixed to the present
     
    private static final Object PRESENT = new Object ();
    The default constructor public HashSet () {//calls the default constructor of the HashMap, creating the map map = new hashmap<e,object> ();
        }///Set constructor public HashSet (collection<? extends e> c) {//create map.        
        Why Call Math.max ((int) (C.size ()/.75f) + 1, 16) and choose a larger tree from (c.size ()/.75f) + 1 and 16?
        First, the description (C.size ()/.75f) + 1//due to the HashMap efficiency (time cost and space cost), the HashMap load factor is 0.75. When HashMap's threshold (threshold =hashmap total size * load factor) < "HashMap actual size",//   You need to double the capacity of the HashMap.
        So, (C.size ()/.75f) + 1 calculates exactly the total space size.
        Next, explain why it is 16. The total size of the hashmap must be 2 times the number of points.
        When the HashMap is created, the specified size is not a number of multiples of 2, and//The HashMap constructor is recalculated to find the number of the exponent times the smallest 2 that is larger than the specified size. Therefore, this designation for 16 is from performance considerations.
        Avoid duplicate computations.
        Map = new hashmap<e,object> (Math.max (int) (C.size ()/.75f) + 1, 16));
    Adds all the elements in the collection (c) to HashSet AddAll (c); }//Specify constructor for HashSet initial capacity and load factor public hashset (int initialcapacity, float loadfactor) {map = new HASHM
    Ap<e,object> (initialcapacity, loadfactor); }//Specifies the constructor for hashset initial capacity public hashset (int initialcapacity) {map = new hashmap<e,object> (init
    ialcapacity); } hashset (int initialcapacity, float loadfactor, Boolean dummy) {map = new Linkedhashmap<e,object&gt
    ;(initialcapacity, Loadfactor); //return HashSet iterator public iterator<e> iterator () {//is actually returning HashMap's "iterator for key set" Retur N map.keYset (). iterator ();
    public int size () {return map.size ();
    public Boolean IsEmpty () {return map.isempty ();
    Public Boolean contains (Object o) {return map.containskey (o);
    ///add Element (e) to HashSet public boolean add (e) {return Map.put (E, PRESENT) ==null;
    The Element (O) Public boolean remove (Object o) {return map.remove (o) ==present in HashSet is deleted;
    public void Clear () {map.clear (); ///Clone a HashSet and return object object public Object Clone () {try {hashset<e> Newset = (Ha
            shset<e>) Super.clone ();
            Newset.map = (hashmap<e, object>) Map.clone ();
        return newset;
        catch (Clonenotsupportedexception e) {throw new Internalerror (); }///java.io.Serializable Write function//will HashSet "total capacity, load factor, actual capacity, all elements" are written to the output stream in private void writeobject (JAVA.IO.OBjectoutputstream s) throws java.io.IOException {//Write out any hidden serialization magic s.de
     
        Faultwriteobject ();
        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 (iterator I=map.keyset (). iterator (); I.hasnext ();)
    S.writeobject (I.next ()); ///java.io.Serializable read function//Will HashSet "total capacity, load factor, actual capacity, all elements" in turn read out private void ReadObject (Java . Io. ObjectInputStream s) throws Java.io.IOException, ClassNotFoundException {//Read in any hidden Serializat
     
        Ion 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); }
    }
}

Description

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.