HashSet随笔
HashSet说白了其实就是HashMap.Entry[capacity], HashMap.Entry实现的链表 相当于LinkedList.
参数loadFactor对其性能有很大影响.
capacity: the number of buckets.
initialCapacity: Default value is 16, 用于初始化数组的槽位, capacity永远 >= initialCapacity 并且capacity永远为2的n次幂 最大值为1<<30.
因为源码已经解释的很清楚了.
1 if (initialCapacity < 0) 2 throw new IllegalArgumentException("Illegal initial capacity: " + 3 initialCapacity); 4 if (initialCapacity > MAXIMUM_CAPACITY) 5 initialCapacity = MAXIMUM_CAPACITY; 6 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 7 throw new IllegalArgumentException("Illegal load factor: " + 8 loadFactor); 9 10 // Find a power of 2 >= initialCapacity 11 int capacity = 1; 12 while (capacity < initialCapacity) 13 capacity <<= 1; 14 15 this.loadFactor = loadFactor; 16 threshold = (int)(capacity * loadFactor); 17 table = new Entry[capacity];
loadFactor: Default value is 0.75, 影响resize容器的频率与内存占用, 越小则需要更多内存占用, 越大则增加get()与put()/putAll()的系统开销.
threshold: 始终为当前capacity*loadFactor, 每次添加数据时会判断size()是否 >= threshold, 大于则resize(). resize()的同时会再次计算新的threshold值.