Java source Code Analysis of the HashSet

Source: Internet
Author: User

http://blog.csdn.net/jzhf2012/article/details/8540696

The purpose of the Java container class is to "save objects", divided into two categories: map--Stores "key-value pairs" of objects; collection--stores independent elements. Collection can also be divided into lists and set two chunks. The list retains the order of the elements, and the set cannot have duplicate elements.

This paper analyzes the most commonly used hashset classes in set, and briefly introduces and contrasts the linkedhashset.

First, the set interface is briefly described.

Each element that is stored in the set must be unique because set does not save duplicate elements. The element that joins the set must define the Equals () method to ensure the uniqueness of the object. Set does not guarantee the order in which elements are maintained. The set has exactly the same interface as the collection.

When set is required without additional restrictions, use hashset as much as possible, as it optimizes speed.

Here is the definition of hashset:

1 public class Hashset<e>2     extends Abstractset<e>3     implements Set<e>, Cloneable, Java.io.Serializable

HashSet inherits the Abstractset and implements the set interface. In fact, Abstractset has implemented the set interface. Abstractset inherits from Abstractcollection, and Abstractcollection implements some methods of collection interface, while the set interface and collection interface are identical, So Abstractset just implements the Abstractcollection not implemented the set interface method and overrides some abstractcollection already implemented methods.

The following are the properties defined by HashSet:

1 private transient hashmap<e,object> map;2 private static Final Object PRESENT = new Object ();

Why do you have a hashmap<e,object>-defined property?

Think about what the characteristics of HashMap: Based on a hash table, store key value pairs, key can not be the same and so on. Key cannot be the same! Does this feature not be the same as set elements and similar? If the set element is treated as a key of the map, does it guarantee that the element is not duplicated?! The answer is yes. But the map stores the key value pair, key has, then value? This is the meaning of the second attribute persent. When you see the Persent property, it is static and final, and its purpose is to store it as value into the map.

To summarize, HashSet is implemented in roughly the following way, through a hashmap storage element, where the element is stored in the HashMap key, and value uses a uniform object.

So it seems hashset should be very simple, should just use the HashMap part of the content to achieve.

Let's look at the other specific code below to verify the above conjecture.

Construction Method:

1//constructor method one: Call the default HashMap constructor method to initialize map 2 public HashSet () {3     map = new hashmap<e,object> (); 4} 5//constructor method Two: According to the given Coll The ection parameter calls the construction method of HashMap (int initialcapacity) to create a hashmap (described in the source code analysis of this constructor HashMap) 6// Call the AddAll method to add elements in C to the HashSet object 7 public HashSet (COLLECTION<? extends e> c) {8     map = new hashmap<e,object> (Math.max (int) (C.size ()/.75f) + 1, 16)); 9     AddAll (c); 10}11//construction Method Three: Constructs a HASHMAP12 public HashSet (int initialcapacity, float loadfactor) that specifies the initialization capacity and load factor {13     map = new Hashmap<e,object> (initialcapacity, loadfactor); 14}15//construction method Four: Constructs a HASHMAP16 public that specifies the initialization capacity HashSet (int initialcapacity) {     map = new hashmap<e,object> (initialcapacity); 18}19// Construction method Five: Constructs a specified initialization capacity and load factor of the LINKEDHASHMAP20//dummy parameter is ignored, just to distinguish the other, including an int, float parameter construction method of HashSet (int initialcapacity, Float Loadfactor, Boolean dummy) {     map = new Linkedhashmap<e,object> (initialcapacity, loadfactor); 23}

The above construction method is simple, only the constructor method two calls the AddAll (collection<? extends E> c) method. The method is defined in Abstractcollection and HashSet owns the method through inheritance.

1 public boolean addall (collection<? extends e> c) {2     Boolean modified = False;3     iterator<? extends e> E = C.iterator (); 4 while     (E.hasnext ()) {5         if (Add (E.next ())) 6         modified = true;7     }8     return modified ; 9}

This method adds elements by traversing the elements in C and then invoking the Add (e) method.

1 public boolean Add (E e) {2     return Map.put (E, PRESENT) ==null;3}

See the Add (E) method simply calls the HashMap (the constructor method provides a way to create the Linkedhashmap, but Linkedhashmap is inherited HashMap, The Put method is also called the put method of HashMap to add e as key,persent as value to the map and determine whether the addition succeeds based on the return value.

Because the HashMap put method returns the corresponding value value if the key already exists, NULL is returned if the key does not exist, so the new element is added to the hashset based on the return null, and if another value is returned the key already exists That the element already exists in the HashSet, and add (e) Returns a result of false. Although the Add (e) return false indicates that HashSet added the element failed, in fact the contents of the map are replaced, and the original value is replaced by Persent.

What if the original value is NULL? In fact, this is not a concern, because the elements added by HashSet, the content of value is persent, there will be no null condition.

Iterator ()

1 public iterator<e> Iterator () {2     return Map.keyset (). Iterator (); 3}

It is clear that the iterator returning is the keyset in HashMap.

Size ()

1 public int size () {2     return map.size (); 3}

The size () method also returns the scale of the map, so HashSet does not define a size property at all.

1 public boolean IsEmpty () {2     return Map.isempty (); 3}

Since size () is a map, the IsEmpty () is naturally a map.

1 public boolean contains (Object o) {2     return Map.containskey (O), 3} 4 public void Clear () {5     map.clear (); 6}  7 public Object Clone () {8     try {9         hashset<e> newset = (hashset<e>) super.clone ();         Newset.map = (Hashmap<e, object>) Map.clone ();         return newset;12     } catch (Clonenotsupportedexception E) {         throw new Internalerror ();     }15}

These methods are not explained.

1 public boolean remove (Object o) {2     return Map.Remove (o) ==present;3}

Remove (Object o) Why do you have to judge the result? Because the value that is stored by the HashSet element is persent, and if the incoming o does not exist, the Remove method of map returns NULL, then the corresponding result is that the remove operation of HashSet should be put back to false, So here we determine whether the removal succeeds based on the returned results.

can only sigh hashmap too strong, HashSet is completely use hashmap to achieve.

Java source Code Analysis of the 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.