The interpretation of HashSet in Java

Source: Internet
Author: User
Tags set set


A HashSet Source Code
The realization of HashSet

For HashSet, it is based on HASHMAP implementation, HashSet the bottom of the HashMap to save all the elements, so HashSet implementation is relatively simple, view HashSet source code, you can see the following code: Java code
public class Hashset<e> extends abstractset<e>
Implements Set<e>, Cloneable, java.io.Serializable {
Use HashMap key to save all elements in HashSet private transient hashmap<e,object> map;
A virtual object object is defined as the value of the HashMap private static final Object PRESENT = new Object (); ...
Initializes a HashSet, and the underlying initializes a HASHMAP public HashSet () {
Map = new hashmap<e,object> (); }
Create HashSet with the specified initialcapacity, loadfactor, or in fact it is created with the corresponding parameters HashMap
Public HashSet (int initialcapacity, float loadfactor) {
Map = new Hashmap<e,object> (initialcapacity, loadfactor); }
Public HashSet (int initialcapacity) {
Map = new hashmap<e,object> (initialcapacity); }
HashSet (int initialcapacity, float loadfactor, Boolean dummy) {
Map = new Linkedhashmap<e,object> (initialcapacity, loadfactor); }
Call Map KeySet to return all key public iterator<e> Iterator ()
{
Return Map.keyset (). iterator (); }




Calling HashMap's size () method returns the number of Entry, and the number of elements in the Set
public int size () {
return Map.size (); }
Call HashMap's IsEmpty () to determine if the HashSet is empty,//When the HashMap is empty, the corresponding HashSet is also empty public boolean isEmpty () {
return Map.isempty (); }
Call HashMap's containskey to determine whether all elements of the specified key//HashSet are stored as public boolean contains (Object O) through the HASHMAP key {
return Map.containskey (o); }
Puts the specified element in HashSet, which is the element that is placed as a key HashMap public boolean add (E e) {
Return Map.put (E, PRESENT) = = NULL; }
The Remove method that calls HashMap removes the specified Entry, and the corresponding element in HashSet is deleted.
public boolean remove (Object o) {
return Map.Remove (o) ==present; }
The clear method of calling Map clears all Entry and clears all elements in HashSet
public void Clear () {
Map.clear (); }     ...    }

As can be seen from the above source program, the implementation of HashSet in fact just encapsulates a HashMap object to store all the collection elements, all the collection elements put into HashSet is actually saved by the key of HashMap, while the HashMap value stores a PR ESENT, which is a static object.
Most of the methods of HashSet are implemented by invoking the HashMap method, so HashSet and HashMap two sets are essentially the same in their implementations.


Two Hashset<e> Object
The objects created by hashset<e> are called collections:
Hashset<string> s= hashset<string>;
Then S is a collection of data that can store string types, and S can call the Add (string s) method to add data of type string to the collection. The data that is added to the collection is called the element of the collection. The collection does not allow the same element, that is, if B is already an element in the collection, then executing the Set.add (b) operation is not valid. Three A detailed approach in hashset<e>
①public boolean Add (E O)--Adds the element specified by the parameter to the collection. (If this collection also
Does not contain the specified element, the specified element is added. )
Parameters:
O-the element that will be added to this collection. Return:
Returns True if the collection does not yet contain the specified element.

②public void Clear ()-Clears the collection so that the collection does not contain any elements.
③public Boolean contains (Object O)--Determines whether the data specified by the parameter belongs to the collection. ()
Parameters:
O-the element whose presence in this collection has been tested.
Return:
Returns True if this collection does not contain the specified element.
④public Boolean IsEmpty ()--Determines whether the collection is empty.
Return:
Returns True if this collection does not contain any elements.
⑤public boolean remove (Object o)--Sets the element specified by the delete parameter.
Parameters:
O-the object that needs to be removed if it exists in this collection.
Return:
Returns True if the collection contains the specified element.
⑥public int Size ()--Returns the number of elements in the collection.
Return:
The number of elements in this collection (the capacity of the collection).
⑦object [] ToArray ()--stores the collection elements in the array and returns the array.
⑧boolean Containsall (HashSet set)--Determines whether the current collection contains the set specified by the parameter.
⑨public Object Clone ()--Gets a cloned object from the current collection, which changes the elements in the object
Changes do not affect the elements in the current collection, and vice versa. Return:
Shallow copy of this collection.

Four Code:


Import Java.util.HashSet;
Class student{String name; int score;
Student (String name, int score) {this.name = name;       This.score = score; }   }
public class testhashset{
public static void Main (string[] args) {
Student zh = new Student ("Zhang San", 77);           Student li = new Student ("John Doe", 68); Student wa = new Student ("Harry", 67);
hashset<student> set = new hashset<student> (); hashset<student> subset = new hashset<student> ();
System.out.println ("Before Add (ZH):" +set.add (ZH)); Set.add (en);
System.out.println ("After Add": "+set.add (ZH)");           Implementation of the Add Method Set.add (WA); Set.add (LI);
Subset.add (WA); Subset.add (LI);
System.out.println ("is subset empty? "+subset.isempty ()); Implementation of IsEmpty method
if (Set.contains (WA)) {
System.out.println ("Set Set contains:" +wa.name); Implementation of the Contains method}
if (Set.containsall (subset)) {
System.out.println ("Set set contains set subset"); }
int number = Subset.size (); The implementation of the size method System.out.println ("+number+" element in the collection subset: ");
Object s[] = Subset.toarray (); Implementation of ToArray method



for (int i=0; i<s.length; i++) {
System.out.printf ("Name:%s, score:%d\n", ((Student) s[i]). Name, ((Student) s[i]). Score); }
Subset.remove (WA); The implementation of the Remove method System.out.println ("After implement remove on subset");
System.out.println ("The Set subset has" +subset.size () + "elements:");
Object a[] = Subset.toarray ();
for (int i=0; i<a.length; i++) {
System.out.printf ("Name:%s, score:%d\n", ((Student) a[i]). Name, ((Student) a[i]). Score); }       }   }
Five Run results
Before Add (ZH): True after Add (en): false is subset empty? False Collection set contains: Harry Collection set containing set subset collection subset has 2 elements in it: Name: John Doe, score: 68 Name: Harry, Score: 67
After implement remove in subset collection subset There are 1 elements: Name: John Doe, score: 68

The interpretation of HashSet in Java

Related Article

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.