Detailed usage of Java HashSet function, storage mechanisms and performance analysis

HashSet storage mechanism:

  • With a length of the underlying storage element array, and the array is always the n-th power of 2, if the incoming length of the array is not n-th power of 2, HashSet it will automatically extend to the n-th power of 2;
  • HashSet constructor:
HashSet(int initialCapacity, float loadFactor)
//initialCapacity——控制底层数组长度
//loadFactor——当HashSet感觉到底层快要满的时候(0.75),会将底层数组容量扩充1倍,
//原来的数组就变成垃圾,等待回收,即rehash(重hash)
//说明:当LoadFactor为0.75时,75%的桶已满,HashSet会分配新的数组;LoadFactor越小,
//越消耗内存;LoadFactor越大,性能越低
//数组越满,才回去“重hash”,越有可能出现链表
  • HashSet into the mechanism:
  1. When all elements add to the mix, the object is invoked HashSet HashCode () method, to obtain an int value;
  2. The int value returned HashCode (), which is calculated in the bottom HashSet [] array of storage locations (indexed array);
  3. If no element to be added is a position (is empty), directly into the can;
  4. If you want to add the element position has been, where it will form a "chain"
  • HashSet take elements of mechanisms:
  1. When we want to take an element, the object is invoked HashSet HashCode () method, to obtain an int value;
  2. The int value returned HashCode (), which calculates the storage position (the index of the array) at a HashSet;
  3. If the location is exactly looking element can be taken directly;
  4. If the location has a list, HashSet to "one by one" in the search list elements

Description: In the best case, the performance is almost HashSet array match, to deposit, withdraw very high performance

  • HashSet two objects are considered equal conditions:
  1. HashCode two objects () is equal to the return value;
  2. Compare the two objects are also returned by equals True
Published 111 original articles · won praise 57 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_38358499/article/details/100631653