The implementation of hash table in Java class Library--hashset

Source: Internet
Author: User

HashSet is implemented based on the implementation--hashmap of the hash table in the Java class Library, unlike HashMap, which holds a single element instead of a key-value pair.

In HashSet, use HashMap to store elements:

private transient hashmap<e,object> map;
As seen from this map type, it stores the hashset element as a HashMap key. Because the value position of the key-value pair is empty, a value is used to occupy the position of the value of the key-value pair:

Private static Final Object PRESENT = new Object ();
present is set to static so that it belongs to a class so that all HashSet instances use this object to save storage space.

Let's take a look at some of the operations in HashSet.

(1) Add an element to the HashSet

    Public boolean Add (E e) {        return Map.put (E, PRESENT) ==null;    }
The put method of HashMap is already mentioned in the implementation--hashmap of the hash table in the Java class Library.

(2) Removing an element from the HashSet

    public boolean remove (Object o) {        return Map.Remove (o) ==present;    }
The Remove method of HashMap is also mentioned in the implementation--hashmap of the hash table in the Java class Library .
(3) See if HashSet contains an element

    Public Boolean contains (Object o) {        return Map.containskey (o);    }
The ContainsKey method of HashMap is also mentioned in the implementation--hashmap of the hash table in the Java class Library .

The implementation of hash table in Java class Library--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.