1. HashSet Overview
HashSet implements the set interface, which is supported by a hash table (actually a hashmap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant. This class allows the use of NULL elements.
2. Implementation of HashSet
If not, it is added to the linked list corresponding to the array index.
------------------------------------------------------------------------------------------
Set implementation class can not have duplicate elements in the collection object, HashSet is the same as he used an identity to determine the elements of the non-repetition, hashset with an algorithm to ensure that hashset elements are not duplicated, hashset using a hashing algorithm, the underlying array to store data. Default initialization capacity 16, load factor 0.75
The method of Hashcode () in the object class is that all subclasses inherit this method, and this method calculates a hash (hash) value return using the hash algorithm, and the hashset will use the hash code value to take the modulus of the array length. Modulo (where the object is to be placed in the array) determines whether the elements in the array are the same as the contents of the objects to be joined, and if they are different, they are added.
Hash algorithm is a hashing algorithm.
Set hs=new HashSet ();
Hs.add (o);
|
O.hashcode ();
|
o% Current Total Capacity (0--15)
|
| No conflicts
If there is a conflict-----------------direct storage
|
| Conflict occurred
| False (Not equal)
O1.equals (O2)-------------------Find a vacancy to add
|
| Yes (equal)
Do not add
The principle of overriding the Hashcode () method:
1. Be sure to return the same hashcode value to the objects that we think are the same
2, try to let those we think that different objects return different hashcode values, otherwise, will increase the probability of conflict.
3, as far as possible to let Hashcode value Liekai (two value with a different or operation can make the result range wider)
The implementation of HashSet is relatively simple, the related HashSet operations are basically directly called the underlying hashmap of the relevant methods to complete, we should save to the object in HashSet hashcode () and Equals (), Since the object is added to the HashSet, the Hashcode method is called first to calculate the hash value of the object, and then the hash method in the HashMap is called according to the hash value, the resulting value & (LENGTH-1) Gets the index of the save position of the object in the HashMap transient entry[] table, and then finds the object that is saved in the array at that index position, and calls the Equals method to compare whether the two objects are equal or not, if the equality is not added. Note: Therefore, the custom class in the collection object to be deposited in hashset must overwrite the hashcode (), Equals () two methods to ensure that the elements in the collection are not duplicated. When overriding the Equals () and Hashcode () methods, the Hashcode () method of the same object returns the same value, overriding the Equals () method to determine its contents. In order to ensure the efficiency, so when covering the Hashcode () method, also try to make different objects as far as possible to return different hash code values.
If the elements in the array and the hashcode () of the object to be joined return the same hash value (the same object), the Equals () method is used to determine whether the contents of the two objects are the same.
------------------------------------------------------------------------------------------
The source code for HashSet is as follows:
[Java]View PlainCopy
- Public class Hashset<e>
- Extends abstractset<e>
- Implements Set<e>, Cloneable, java.io.Serializable
- {
- Static final long serialversionuid = -5024744406713321676l;
- The underlying uses HashMap to hold all the elements in the hashset.
- Private transient hashmap<e,object> map;
- Defines a dummy object as the value of HashMap, which defines this object as static final.
- Private static final Object PRESENT = new Object ();
- /**
- * 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.
- */
- Public HashSet () {
- Map = new hashmap<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 specified
- * The initial capacity of all elements in collection to create a hashmap.
- * @param c where the elements will be stored in the collection in this set.
- */
- Public HashSet (COLLECTION<? extends e> c) {
- Map = New Hashmap<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.
- * @param initialcapacity initial capacity.
- * @param loadfactor loading factor.
- */
- Public HashSet (int initialcapacity, float loadfactor) {
- Map = New Hashmap<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.
- * @param initialcapacity initial capacity.
- */
- Public HashSet (int initialcapacity) {
- Map = new hashmap<e,object> (initialcapacity);
- }
- /**
- * Constructs a new empty-link hash collection with the specified initialcapacity and loadfactor.
- * This constructor is for package access, not public, and is actually just a support for linkedhashset.
- *
- * The actual underlying will be implemented with an empty Linkedhashmap instance constructed with the specified parameters.
- * @param initialcapacity initial capacity.
- * @param loadfactor loading factor.
- * @param dummy mark.
- */
- HashSet (int initialcapacity, float loadfactor, boolean dummy) {
- Map = New Linkedhashmap<e,object> (initialcapacity, loadfactor);
- }
- /**
- * Returns an iterator that iterates over the elements in this set. The order of the returned elements is not specific.
- *
- * The underlying actual call to the underlying HashMap keyset to return all keys.
- * Visible hashset elements, just stored in the underlying HashMap key,
- * Value uses a static final object identifier.
- * The iterator that iterates over the elements in this set @return.
- */
- Public iterator<e> Iterator () {
- Return Map.keyset (). iterator ();
- }
- /**
- * Returns the number of elements in this set (capacity of Set).
- *
- * The size () method of the underlying actual call to HashMap returns the number of entry, and the number of elements in the set is obtained.
- * @return The number of elements in this set (capacity of Set).
- */
- public int size () {
- return Map.size ();
- }
- /**
- * Returns True if this set contains no elements.
- *
- * The underlying actual call to HashMap IsEmpty () determines whether the hashset is empty.
- * @return Returns True if this set contains no elements.
- */
- Public Boolean IsEmpty () {
- return Map.isempty ();
- }
- /**
- * Returns True if this set contains the specified element.
- * More precisely, when and only if this set contains a satisfying (o==null? E==null:o.equals (e))
- * When the E element returns true.
- *
- * The underlying actual call to HashMap ContainsKey determines whether the specified key is included.
- * @param o The existence of the element that has been tested in this set.
- * @return Returns True if this set contains the specified element.
- */
- Public Boolean contains (Object o) {
- return Map.containskey (o);
- }
- /**
- * If the specified element is not already contained in this set, the specified element is added.
- * More specifically, if this set does not contain the content (E==null? E2==null:e.equals (E2))
- * element 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.
- *
- * The underlying actually puts the element as key into the HashMap.
- * Because the put () method of HashMap adds Key-value pair, when the new is placed in the entry of HashMap key
- * Same as key with entry in the Set (Hashcode () return value is equal, also return true by equals),
- * The value of the newly added entry will overwrite the value of the original entry, but there will be no change to key.
- * Therefore, if an existing element is added to HashSet, the newly added collection element will not be placed in the HashMap,
- * The original element will not have any changes, which satisfies the feature that the element in set does not repeat.
- * @param e is added to the element in this set.
- * @return Returns True if this set does not already contain the specified element.
- */
- Public Boolean Add (E e) {
- Return Map.put (E, PRESENT) = =null;
- }
- /**
- * If the specified element is present in this set, it is removed.
- * More specifically, if this set contains an element e that satisfies (o==null. E==null:o.equals (e)),
- * Remove it. Returns True if this set already contains the element
- * (or: Returns True if this set changes because of a call). (Once the call returns, the set no longer contains the element).
- *
- * The lower layer actually calls HashMap's Remove method to delete the specified entry.
- * @param o An object that needs to be removed if it exists in this set.
- * @return Returns True if the set contains the specified element.
- */
- Public boolean remove (Object o) {
- return Map.Remove (o) ==present;
- }
- /**
- * Removes all elements from this set. When this call returns, the set will be empty.
- *
- * The lower layer actually calls HashMap's clear method to empty all elements in the entry.
- */
- Public void Clear () {
- Map.clear ();
- }
- /**
- * 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.
- */
- 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 ();
- }
- }
- }
HashSet Implementation principle