Java HashSet set of hashes


HashSet

  • Set interface and implement AbstractSet extended, using a hash table to create a stored set of classes, and the hash (hash table) for storing information is called hashing mechanism;
  • Hashing: a content key is used to determine a single value, called a hash code (the hashCode), hash code is used as the index key storage coupled to data, which keywords to hash code is performed automatically, so the hash can not see the code itself, the code can not be directly indexed hash table, also make a large collection of the Add (), running contains (), remove (), size () method and the like the same time;
  • HashSet calls when calls element hashCode () method, to obtain its hash code (the hashCode), the storage location in the hash code determined in accordance with the set of improved storage speed;
  • key, value can be the value of the HashMap object is null, but allows up to a null value of the element;
  • HashSet can not determine the order of the element, normally not intervene to create a set of permutations, if you want to sort, it is recommended to use TreeSet ;

1. Constructor

Construction method Explanation
HashSet() Constructs an empty Set collection
HashSet(Collection c) Construct a set of elements comprising the set of
HashSet(int capacity) Construct a set of initial capacity Set
HashSet(int capacity, float fillRatio) When the filling ratio of the specified capacity (known as loading capacity), the filling ratio must be between 0.0 and 1.0, determines how much upward adjustment set of hashes size before being filled, when the number of elements is greater than the capacity of the hash table is filled than x, hash collection was expanded, the default value is 0.75

2. Remove the principle of repeating elements

HashSet deduplication principle


3. Use of class

import java.util.HashSet;
import java.util.Iterator;

public class test {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add("12");
        hs.add("34");
        hs.add("56");
        hs.add("12");
        System.out.println(hs.size());//3
        Iterator it = hs.iterator();
        while (it.hasNext()) {
            System.out.print(it.next()+" ");
        }
    }
}

4. LinkedHashSet

Details: LinkedHashSet chain hash set

Published 59 original articles · won praise 60 · views 1579

Guess you like

Origin blog.csdn.net/Regino/article/details/104549599