Java Hash List Hash table

Source: Internet
Author: User
Tags set set

Java Hash List Hash table

@author Ixenos

Hash table, HashTable, HashMap, HashSet

    • Hash table is a data structure
    • Hash table computes an integer for each object that is called hash code
      • Hash code is an integer generated by the object's instance field, and objects with different data fields will produce different hash code
      • If the custom class is responsible for implementing the Hashcode method of this class, be aware that it is compatible with the Equals method, that is, if A.equals (b) is true, A and B hash code must be the same

    • In Java, hash table is implemented with a list of linked lists (that is, the array element is a linked list), and each list is called a bucket bucket, java.util.hashtable<k,v>.
      • Buckets:buckets for collecting elements with the same hash code. To find the position of an object in a table, calculate its hash code, and then take the sum of the buckets, and get the index of the bucket that holds the element.

         The image comes from "Core Java"

        • If there are no other elements in the bucket, the element is inserted directly into the bucket, and if there are elements in the bucket, you need to compare the new object with all the objects in the bucket to see if the object already exists, and if it does not exist, modify the list node index to join the bucket If the bucket is full, this phenomenon is called hash conflict hash collision, and you need to compare the new object with all the objects in the bucket to see if the object already exists
      • Hash Conflict:hash collision, if the element inserted into the hashtable too many, it will increase the likelihood of hash collision, reduce performance, so to specify an initial number of buckets. Typically, the number of buckets is set to the 75%~150% of the expected number of elements
        • "API documentation"
        •  public class  Hashtable<k,v>  extends Dictionar Y<k,v>implements Map<k,v>, cloneable, Serializable 

          null   objects can be used as keys or values. in order to successfully store and get objects in a hash table, objects used as keys must implement &NBSP; Hashcode   methods and   equals   method. Hashtable   instance has two parameters affecting its performance: initial capacity   and load factor . capacity   is the number of buckets   in the hash table, and initial capacity   is the capacity at the time of the Hashtable creation. Note that the status of the hash table is   open : In the case of a "hash conflict", a single bucket stores multiple entries that must be searched sequentially. load factor   is a measure of how full a hash table can be before its capacity increases automatically. Both the initial capacity and the load factor are just hints for the implementation. The specifics of when and whether to invoke the rehash method depend on the implementation.

      • re-hash:rehashed, if the estimate is too low, Hashtable is too full, you need to hash rehashed if the loading factor is 0.75, and the table more than 75% of the position has been filled in the element, This hashtable will double the number of barrels and then hash rehashed

  • hash table can be used to implement several important data structures
    • Set type: Set is a collection of elements without repeating elements (collection), the Add method first finds the object to be added in set set, and does not exist to add
    • such as those in the Java class Library.HashSet, it implements the set based on hash table (based on HashMap)
      • HashSet internally maintains a Hashmap<e,object> object for storing set objects , shielding the keys in the map, and most of the methods are implemented using the HashMap method.
      •  Public class Hashset<e> extends abstractset<e> implements Set<e>, cloneable,    java.io.serializable{  Private transient hashmap<e,object> map;    ...      Public New Hashmap<>();}    ...}
      • such as the implementation of the Contains method
      • //hashset contains method source code (with the help of HashMap method) Public Booleancontains (Object o) {returnMap.containskey (o); } //source code from the HashMap FinalNode<k,v> GetNode (inthash, Object key) {Node<k,v>[] tab; Node<k,v> First, E;intN;        K K; if(tab = table)! =NULL&& (n = tab.length) > 0 &&( First= tab[(n-1) & hash])! =NULL) {            if(First.hash = = Hash &&//Always check first node(k = first.key) = = Key | | (Key! =NULL&&Key.equals (k)))) returnFirst ; if((E = first.next)! =NULL) {                if(FirstinstanceofTreeNode)return((treenode<k,v>). Gettreenode (hash, key);  Do {                    if(E.hash = = Hash &&((k= e.key) = = Key | | (Key! =NULL&&Key.equals (k)))) returne; }  while((E = e.next)! =NULL); }        }        return NULL; }     Public BooleanContainsKey (Object key) { //HashSet contains method call returnGetNode (hash (key), key)! =NULL; }
          • As you can see from the source code: The Contains method can be used to quickly see if an element is already in the set because it looks for an element in only one bucket, without having to look at all the elements in the collection
          • The HashSet iterator accesses all buckets in turn, and since the hash disperses the elements across the table (HashSet should be used only if you don't care about the order of the elements in the collection), the order in which they are accessed is almost random (which is, of course, "fixed").
      • Since the hash code of the element determines the bucket, so when modifying the internal characteristics (instance domain) of the elements in set set, be careful to change the position of the element in the data structure when the hash code changes

Java Hash List Hash table

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.