Java Collection-hashset

Source: Internet
Author: User
Tags new set shallow copy

HashSet Overview

For HashSet, It is based on HashMap implementation, the underlying use of HashMap to save elements, so if the HashMap more familiar with, then learning HashSet is also very easy.

Let's take a look at the simplest constructors and several member variables to prove what we said above, the bottom of the HashSet is HashMap:

Private transientHashmap<e,object>map; //Dummy value to associate with a Object in the backing Map    Private Static FinalObject PRESENT =NewObject (); /*** Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial Capaci     Ty (+) and load factor (0.75). */     publicHashSet () {map=NewHashmap<>(); }

In fact, in the English note has been said to be more clear. First there is a HASHMAP member variable, which we initialize in the constructor of HashSet, by default initial capacity to 16,load factor is 0.75.

The realization of HashSet

For HashSet, It is based on HashMap implementation, HashSet the underlying use HASHMAP to save all elements, so HashSet implementation is relatively simple, related HashSet operations, basically directly call the underlying HASHMAP related methods to complete , we should overwrite hashcode () and equals () for objects saved to HashSet

Construction method
/*** The default parameterless constructor constructs an empty hashset. * * The actual underlying will initialize an empty HashMap and use the default initial capacity of 16 and load factor 0.75. */ publicHashSet () {map=NewHashmap<e,object>();}/*** Constructs a new set containing the elements in the specified Collection. * * The actual underlying uses the default load factor of 0.75 and is sufficient to contain the initial capacity of all elements in the specified collection to create a hashmap. * @paramc The elements in this set will be stored in the Collection. */ publicHashSet (collection<?extendsE>C) {map=NewHashmap<e,object> (math.max (int) (c.size ()/.75f) + 1, 16)); AddAll (c);}/*** Constructs an empty hashset with the specified initialcapacity and Loadfactor. * * The actual bottom layer constructs an empty hashmap with corresponding Parameters. * @paraminitialcapacity Initial Capacity. * @paramloadfactor Load Factor. */ publicHashSet (intinitialcapacity,floatLoadfactor) {map=NewHashmap<e,object>(initialcapacity, loadfactor);}/*** Constructs an empty hashset with the specified Initialcapacity. * * The actual bottom layer constructs an empty hashmap with corresponding parameters and load factor Loadfactor of 0.75. * @paraminitialcapacity Initial Capacity. */ publicHashSet (intInitialcapacity) {map=NewHashmap<e,object>(initialcapacity);}/*** Constructs a new empty-link hash collection with the specified initialcapacity and Loadfactor. This constructor is for package access, is not public, * actually is only support for Linkedhashset. * * The actual underlying will be implemented with an empty Linkedhashmap instance constructed with the specified Parameters. * @paraminitialcapacity Initial Capacity. * @paramloadfactor Load Factor. * @paramDummy Tag. */HashSet (intinitialcapacity,floatloadfactor,BooleanDummy) {map=NewLinkedhashmap<e,object>(initialcapacity, loadfactor);}
Add method
/**@param @return */public boolean add (e e) {    return map.put (e, PRESENT) = =null;}

If the specified element is not already contained in this set, the specified element is Added. More specifically, If this set does not contain an element e2 that satisfies (e==null. e2==null:e.equals (e2)), The specified element e is added to this set. If this set already contains the element, the call does not change the set and returns False. But the bottom layer actually puts the element as key into the HashMap. Think for a second why?

Since the HashMap put () method adds the Key-value pair, the key is the same as the key in the Entry of the set (the hashcode () return value is equal and returns true by equals in the Entry of the new HashMap. ), the value of the newly added Entry will overwrite the value of the original Entry (value in HashSet PRESENT ), but the key will not change, so if an existing element is added to HashSet, the newly added collection element will not be In hashmap, the original element will not change any more, which satisfies the feature that the element in Set does not repeat.

This method returns true if it is added that does not exist in HashSet, or False if the added element already exists. The reason for this is the put method we mentioned earlier about HASHMAP. This method returns NULL when a Key-value pair is added that does not duplicate the Key.

Remaining methods
  /*** Returns True if this set contains the specified Element.     * More specifically, returns True when and only if this set contains an e element that satisfies (o==null e==null:o.equals (e)).     * * The underlying actual call to HashMap ContainsKey determines whether the specified key is Included. * @paramo The element that has been tested in this Set. * @returnreturns True if this set contains the specified Element. */     public Booleancontains (Object o) {returnMap.containskey (o); }    /*** If the specified element is present in this set, it is Removed. rather, If this set contains an element e that satisfies (o==null. e==null:o.equals (e)), * It is Removed.     If this set already contains the element, returns True * * The lower layer actually calls Hashmap's Remove method to delete the specified entry. * @paramo An object that needs to be removed if it exists in this set. * @returnreturns True if the set contains the specified Element. */     public BooleanRemove (Object o) {returnMap.Remove (o) = =PRESENT; }    /*** Returns a shallow copy of this hashset instance: the elements themselves are not copied.     * * The underlying actually calls Hashmap's clone () method, Gets the shallow copy of the hashmap, and sets it to Hashset. */     publicObject clone () {Try{HashSet<E> Newset = (hashset<e>)Super. Clone (); Newset.map= (hashmap<e, object>) Map.clone (); returnnewset; } Catch(clonenotsupportedexception E) {Throw NewInternalerror (); }    }}
Related instructions
    1. For the implementation principle of the related HashMap, please refer to my previous review: HASHMAP implementation Principle.
    2. For objects saved in HashSet, be aware that their equals and hashcode methods are correctly overridden to guarantee the uniqueness of the objects that are Placed. These two methods are more important, I hope you in the future development process need to pay attention to.

Java Collection-hashset

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.