Java Collection Framework-hashset__java

Source: Internet
Author: User

public class Hashset<e> extends abstractset<e> implements Set<e>, Cloneable, Java.io.Serializabl

    e {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 ();
    Public HashSet () {map = new hashmap<e,object> (); Public HashSet (collection<? extends e> c) {map = new hashmap<e,object> ((int) (Math.max () c.size
   ) + 1, 16);
    AddAll (c); Public hashset (int initialcapacity, float loadfactor) {map = new hashmap<e,object> (initialcapacity, LOADF
    Actor);
    Public hashset (int initialcapacity) {map = new hashmap<e,object> (initialcapacity); } hashset (int initialcapacity, float loadfactor, Boolean dummy) {map = new linkedhashmap<e,object> (initialc
    Apacity, Loadfactor); } public ITERATOR&LT
    E> iterator () {return Map.keyset (). iterator ();
    public int size () {return map.size ();
    public Boolean IsEmpty () {return map.isempty ();
    Public Boolean contains (Object o) {return map.containskey (o);
    Public boolean Add (E. e) {return Map.put (E, PRESENT) ==null;
    public boolean remove (Object o) {return map.remove (o) ==present;
    public void Clear () {map.clear ();
       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 (); } private void WriteObject (Java.io.ObjectOutputStream s) throws java.io.IOException {//Write OU

        T any hidden serialization 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 (iterator I=map.keyset (). iterator (); I.hasnext ();)
    S.writeobject (I.next ());
   } private void ReadObject (Java.io.ObjectInputStream s) throws Java.io.IOException, ClassNotFoundException {

        Read 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); }
    }
}

HashSet implements the set interface, HashSet does not guarantee the order of the iterator, especially the order permanence, hashset only a null element is allowed, for HashSet, it is based on the HashMap to achieve , The bottom layer uses HashMap to save elements. 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-step access to the set. HashSet the iterator returned through the iterator () is fail-fast.

HashSet Property Description:

private transient hashmap<e,object> map;


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

The first constant: map, which shows that the bottom of the hashset is to hold the data with HashMap.

The second constant: Present, because the set uses only the HashMap key, a constant object class is defined here to act as the value of HashMap.

Therefore, it is further demonstrated that the hashset is implemented with HashMap, but only HashMap Key,value are populated with object objects.

Here is the new object, why not NULL, the new object will be in the heap memory space, NULL is no heap of memory to open up space. If declared null, it can cause nullpointexcetion, so in order to avoid this, you should open a 8 byte space to save an object.

HashSet Construction Method:

Initializes a map using the default capacity size of HashMap 16 and the default load factor 0.75 to construct a hashset

Public HashSet () {
Map = new hashmap<e,object> ();
}

/**
* Constructs a hashset that specifies the collection parameter, not just set, as long as the container that implements the collection interface can
*/
Public HashSet (collection<? extends e> c) {
Map = new Hashmap<e,object> (Math. Max (int) (C.size ()/.75f) + 1, 16));
Using the iterator iterator implemented by collection, add the elements of the set C into the HashSet
AddAll (c);
}

/**
* Initializes the map with the specified initial capacity size and load factor, constructing a hashset
*/
Public hashset (int initialcapacity, float loadfactor) {
Map = new Hashmap<e,object> (initialcapacity, loadfactor);
}

/**
* A construction method that is not disclosed externally (default defaults modification), the bottom is constructed linkedhashmap,dummy is only a marked parameter, no specific meaning
*/
HashSet (int initialcapacity, float loadfactor, Boolean dummy) {
Map = new Linkedhashmap<e,object> (initialcapacity, loadfactor);
}

Only the last constructed method has a write difference, where the linkedhashmap is constructed, the method is not publicly available, is actually provided to Linkedhashset, and the third parameter dummy is meaningless, just to differentiate the other constructs.

Boolean contains (object O): Its underlying invocation is Hashmap.containskey (object key) to determine whether a specified key is included

hashset Add (E E): It calls the put (K key, V value) method in the underlying HashMap, first determining whether the element (that is, key) exists, if it does not exist, inserts it, and if it does not, So there's no duplicate values in the HashSet.

If the specified element is not already contained in this set, the specified element is added
Public boolean Add (E e) {
Return Map.put (E, PRESENT) ==null;
}

bottom: When an element is deposited into the HashSet collection, HashSet calls the object's Hashcode () method to get the Hashcode value of the object and then determines where the object is stored in the HashSet based on that value. In a hash set, two equal elements cannot be stored at the same time, and the criterion for determining the equality of two elements is that two objects are equal through the Equals method and the return value of the Hashcode method for two objects is equal.

Note: for objects saved in HashSet, be careful to override their equals and hashcode methods to ensure the uniqueness of the objects you put in. hashset Remove (Object O), Clear ():

If the specified element exists in this set, it is removed
public boolean remove (Object o) {
return Map.Remove (o) ==present;
}
Remove all elements from this set
public void Clear () {
Map.clear ();
}

Size (), IsEmpty ()

Returns the number of elements in this set
public int size () {
return Map.size ();
}
Returns True if this set does not contain any elements
public Boolean IsEmpty () {
return Map.isempty ();
}

HashSet iterator:

Returns an iterator that iterates over the elements in this set
Public iterator<e> iterator () {
Return Map.keyset (). iterator (); Hashmap.keyset () returns the key set in the <key, value> pair
}

Write functions that support serialization WriteObject (Java.io.ObjectOutputStream s) and read function ReadObject (Java.io.ObjectInputStream s):

Java.io.Serializable write function that writes the HashSet "total capacity, load factor, actual capacity, all elements" to the output stream
private void WriteObject (Java.io.ObjectOutputStream s)
Throws Java.io.IOException {
Write out any hidden serialization 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);
}

The java.io.Serializable read function, which reads out the HashSet "total capacity, load factor, actual capacity, all elements" in turn
private void ReadObject (Java.io.ObjectInputStream s)
Throws Java.io.IOException, ClassNotFoundException {
Read in any hidden serialization magic
S.defaultreadobject ();
Read capacity and verify non-negative.
int capacity = S.readint ();
if (capacity < 0) {
throw new Invalidobjectexception ("Illegal capacity:" +
capacity);
}
Read load factor and verify positive and non NaN.
float loadfactor = S.readfloat ();
if (loadfactor <= 0 | | Float.isnan (Loadfactor)) {
throw new Invalidobjectexception ("Illegal load factor:" +
Loadfactor);
}
Read size and verify non-negative.
int size = S.readint ();
if (Size < 0) {
throw new Invalidobjectexception ("Illegal size:" +
size);
}
Set the capacity according to the size and load factor ensuring
The HashMap is in least 25% full but clamping to maximum capacity.
capacity = (int) math.min (size * math.min (1/loadfactor, 4.0f),
hashmap.maximum_capacity);
Create backing HashMap
Map = ((hashset<?>) this) instanceof Linkedhashset?
New linkedhashmap<e,object> (capacity, loadfactor):
New hashmap<e,object> (capacity, loadfactor));
Read in the ' all elements ' proper order.
for (int i=0; i<size; i++) {
@SuppressWarnings ("Unchecked")
E e = (e) s.readobject ();
Map.put (E, PRESENT);
}
}





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.