Java Collection-hashset

Source: Internet
Author: User

The HashSet class, which is a class that exists in the Java.util package. Also known as a collection, the container can only store objects that are not duplicates. The bottom layer is stored by HashMap, because HashSet can not be repeated, you know HashMap key can not be repeated to understand this principle, so for hashmap very familiar with the hashset will be able to quickly know the bottom-level implementation. HashMap Portal (HashMap source analysis).

HashSet Overview

This class implements the set interface, which is supported by a hash table (actually a hashmap instance). There is no guarantee for the iteration order of the set; In particular, there is no guarantee that this order will persist (not guaranteeing the order of the looping elements, so it may be ordered or possibly unordered), and this class allows null elements.

This class of basic operations provides a stable time performance for add,remove,contains and size, assuming that the hash function correctly disperses elements in the bucket. Iterating the collection takes time proportional to the sum of the HashSet instance's size (number of elements) and the "Capacity" (number of buckets) of the background HashMap instance. Therefore, if iterative performance is important, it is important not to set the initial capacity too high (or the load factor is too low).

Note that this implementation is out of sync. If multiple threads access the hash set concurrently, and at least one thread modifies the collection, it must be synchronized externally. This is usually done by synchronizing on an object in the natural encapsulation collection.

If no such object exists, the collection should be "wrapped" using the Collections.synchronizedset method. This is best done at creation time to prevent accidental non-synchronous access sets:

Set s = collections.synchronizedset (new HashSet (...));

The iterator method returned by this class is a quick failure: If the collection is modified at any time after the iterator is created, the iterator throws the concurrentmodificationexception exception in any way except through the iterator's own remove method. As a result, when concurrent modification, the iterator will soon fail, rather than the uncertain behavior in the uncertain time of the future.

Note that the fast failure behavior of iterators is not guaranteed because, in general, no hard guarantees can be made in the case of a concurrent modification of a different step. Fail-fast Iterators will try to throw concurrentmodificationexception exceptions. Therefore, the correctness of writing a program that relies on the exception is wrong: The fast failure behavior of the iterator can only be used to detect errors. (The above translation in JDK1.7, there are errors please point out)

HashSet Source Code Analysis 2.1, definition

public class Hashset<e> extends abstractset<e> implements Set<e>, Cloneable, java.io.Serializable

Inherits Abstractset, which overrides the Equals () and Hashcode () methods to ensure that two equal sets return the same hash code. If two sets are of equal size and contain the same elements, then the two sets are equal. By definition, the Distributed column code is the sum of the concentrated element hash codes. Therefore, regardless of the internal order of the set, two equal gatherings report the same hash code (Baidu Encyclopedia).

The set interface is implemented, and set defines some basic operations of the set, such as Add, remove, and so on. The Clone interface Cloneable is implemented, and the serialized interface is serializable.

2.2. Properties

Static final Long Serialversionuid = -5024744406713321676l;//sequence version number

Private transient hashmap<e,object> map;//hashmap,e is the key, Object is the value, is not see the underlying things, haha

Private static Final Object PRESENT = new Object ()//The virtual value associated with the object that supports the map has three attributes and is simple and rude.

2.3. Construction method
 Public HashSet () {// constructs a new empty collection; the background HashMap instance has a default initial capacity (16) and a load factor (0.75).            New hashmap<>(); }
     Public extends E> c) {// constructs a new collection that contains the elements in the specified collection. The HashMap is created with the default load factor (0.75), and the initial capacity is sufficient to contain the elements in the specified collection.         New hashmap<> (Math.max ((int) (c.size ()/.75f) + 1, +));//If c.size/  A value of 0.75 is greater than 16 and the size is c.size/0.75+1, otherwise the default is.        AddAll (c); }
 Public HashSet (intfloat loadfactor) {// constructs a new empty collection; the background HashMap instance has the specified initial capacity and the specified load factor.         New hashmap<>(initialcapacity, loadfactor);//initial capacity, load factor}
 Public HashSet (int initialcapacity) {// constructs a new empty collection; the background HashMap instance has the specified initial capacity and default load factor (0.75).           New hashmap<>(initialcapacity); }
HashSet (intfloatboolean dummy) {// constructs a new, empty linkedhashmap. (This package private constructor is used only by Linkedhashset.) The suffix HashMap instance is a linkedhashmap with the specified initial capacity and a specified load factor.           New linkedhashmap<>(initialcapacity, loadfactor); }
2.4. Add method
 Public Boolean Add (e e) {        return map.put (e, PRESENT) = =null;   Map added, finally see the bottom is map. }
2.5. Remove method
 Public boolean remove (Object o) {// If present, removes the specified element from the collection.          return map.remove (o) = =PRESENT; }
2.6. Clear method
   Public void Clear () {// removes all elements from the collection. After this call is returned, the collection will be empty.          map.clear ();//Use Map's clear}
2.7. Clone method
 PublicObject Clone () {//returns a shallow copy of this <tt> HashSet </tt> instance: The element itself is not cloned.        Try{HashSet<E> Newset = (hashset<e>)Super. Clone ();//hashset CloningNewset.map = (hashmap<e, object>) Map.clone ();//Map Clones            returnNewset; } Catch(clonenotsupportedexception e) {Throw NewInternalerror (); }}
HashSet Summary

HashSet the bottom of the use of HASHMAP implementation, as long as the hashmap familiar, hashset without pressure. Here are some things to keep in mind:

1, hashset can insert null.

2. Elements of HashSet cannot be duplicated.

3. The traversal of HashSet is likely to be unordered in order.

  

Java Collection-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.