Module  java.base
Software package  java.util

Class HashSet<E>

  • Parameter Type
    E- The type of elements maintained by this set
    All implemented interfaces
    Serializable , Cloneable , Iterable<E> , Collection<E> , Set<E>
    Known direct subclasses:
    JobStateReasons , LinkedHashSet

    public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, Serializable
    this class implementsSetinterface, backed by a hash table (actually isHashMapsupported by the instance). It does not guarantee the iteration order of the collection; In particular, it does not guarantee that the order will remain unchanged over time. this class allowsnullElement.

    This class provides basic operations (constant-time performanceadd , remove , containsandsize), assuming the hash function distributes the correct elements among the buckets. The time required to iterate over this collection is proportional toHashSetThe size of the instance (number of elements) plus the backingHashMapProportional to the sum of the "capacities" (number of buckets) of the instances. Therefore, if iteration performance is important, it is very important not to set the initial capacity too high (or the load factor too low).

    Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one thread modifies the set, thenRequiredSynchronize externally. This is typically accomplished by synchronizing on an object that naturally encapsulates the collection. If such an object does not exist, you should useCollections.synchronizedSetThe method "wraps" theSet 。 This is best done at creation time to prevent accidental unsynchronized access to the collection:

      Set s = Collections.synchronizedSet(new HashSet(...)); 

    This type ofiteratorThe iterator returned by the method isfail-fast: If the set is modified at any time after the iterator is created, except through the iterator's ownremoveExcept for the method, the iterator throwsConcurrentModificationException 。 Therefore, in the case of concurrent modification, the iterator fails fast and cleanly, rather than risking arbitrary, non-deterministic behavior at an unspecified time in the future.

    Please note that the fail-fast behavior of iterators cannot be guaranteed, because in general, it is impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw on a best-effort basisConcurrentModificationException 。 Therefore, it is incorrect to write programs that depend on this exception to ensure their correctness:The fail-fast behavior of an iterator should be used only to detect bugs.

    This type isJava Collections Frameworkthe member.

    Starting from the following version:
    1.2
    See also:
    Collection , Set , TreeSet , HashMap , Serialized Form
    • Constructor Detail

      • HashSet

        public HashSet()
        Constructs a new empty set; SupportedHashMapInstances have a default initial capacity (16) and load factor (0.75).
      • HashSet

        public HashSet​(Collection<? extends E> c)
        Constructs a new collection containing the elements in the specified collection. HashMapCreated with the default load factor (0.75), the initial capacity is sufficient to contain the elements in the specified collection.
        Parameter
        c - cThe collection whose elements are to be placed into this set
        Exception
        NullPointerException- If the specified collection is null
      • HashSet

        public HashSet​(int initialCapacity,
                       float loadFactor)
        Constructs a new empty set; BackupHashMapThe instance has the specified initial capacity and the specified load factor.
        Parameter
        initialCapacity- The initial capacity of the hash map
        loadFactor- The load factor of the hash map
        Exception
        IllegalArgumentExceptionIf the initial capacity is less than zero, or the load factor is non-positive
      • HashSet

        public HashSet​(int initialCapacity)
        Constructs a new empty set; SupportedHashMapThe instance has the specified initial capacity and the default load factor (0.75).
        Parameter
        initialCapacity- The initial capacity of the hash table
        Exception
        IllegalArgumentException- If the initial capacity is less than zero
    • Method Detail

      • size

        public int size()
        Returns the number of elements in this collection (cardinality).
        Specified by:
        sizeIn the interfaceCollection<E>
        Specified by:
        sizeIn the interfaceSet<E>
        Result
        The number of elements in this set (cardinality)
      • isEmpty

        public boolean isEmpty()
        If this collection contains no elements, returnstrue 。
        Specified by:
        isEmptyIn the interfaceCollection<E>
        Specified by:
        isEmptyIn the interfaceSet<E>
        Override:
        isEmptyClassAbstractCollection<E>
        Result
        trueIf this set contains no elements
      • contains

        public boolean contains​(Object o)
        Returns if this set contains the specified element.true 。 More formally, returntrueIf and only if the elements contained in this sete, makingObjects.equals(o, e) 。
        Specified by:
        containsIn the interfaceCollection<E>
        Specified by:
        containsIn the interfaceSet<E>
        Override:
        containsIn classAbstractCollection<E>
        Parameter
        oThe element whose presence in this set is to be tested
        Result
        trueIf this set contains the specified element
      • add

        public boolean add​(E e)
        If the specified element does not yet exist, it is added to this collection. More formally, the specified elementeThis set, if set does not contain elements.e2Such thatObjects.equals(e, e2) 。 If this set already contains the element, the call will keep the set unchanged and returnfalse 。
        Specified by:
        addIn the interfaceCollection<E>
        Specified by:
        addIn the interfaceSet<E>
        Override:
        addIn classAbstractCollection<E>
        Parameter
        e- The element to be added to this set
        Result
        trueIf this set does not already contain the specified element
      • remove

        public boolean remove​(Object o)
        Removes the specified element from this collection, if it is present. More formally, removes the elemente, makingObjects.equals(o, e), if this collection contains such an element. If this set contains an element, then returnstrue(or equivalently, if this collection changed as a result of the call). (Once the call returns, the collection will not contain the element.)
        Specified by:
        removeIn the interfaceCollection<E>
        Specified by:
        removeIn the interfaceSet<E>
        Override:
        removeClassAbstractCollection<E>
        Parameter
        oThe object to be removed from this set, if present
        Result
        trueIf the collection contains the specified element
      • clear

        public void clear()
        Removes all elements from this set. After this call returns, the set will be empty.
        Specified by:
        clearIn the interfaceCollection<E>
        Specified by:
        clearIn the interfaceSet<E>
        Override:
        clearClassAbstractCollection<E>
      • clone

        public Object clone()
        Return thisHashSetA shallow copy of the instance: the elements themselves are not cloned.
        Override:
        cloneClassObject
        Result
        A shallow copy of this set
        See also:
        Cloneable