可以看源码中怎么设计的。- /**
- * Rehashes the contents of this map into a new array with a
- * larger capacity. This method is called automatically when the
- * number of keys in this map reaches its threshold.
- *
- * If current capacity is MAXIMUM_CAPACITY, this method does not
- * resize the map, but sets threshold to Integer.MAX_VALUE.
- * This has the effect of preventing future calls.
- *
- * @param newCapacity the new capacity, MUST be a power of two;
- * must be greater than current capacity unless current
- * capacity is MAXIMUM_CAPACITY (in which case value
- * is irrelevant).
- */
- void resize(int newCapacity) {
- Entry[] oldTable = table;
- int oldCapacity = oldTable.length;
- if (oldCapacity == MAXIMUM_CAPACITY) {
- threshold = Integer.MAX_VALUE;
- return;
- }
- Entry[] newTable = new Entry[newCapacity];
- boolean oldAltHashing = useAltHashing;
- useAltHashing |= sun.misc.VM.isBooted() &&
- (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
- boolean rehash = oldAltHashing ^ useAltHashing;
- transfer(newTable, rehash);
- table = newTable;
- threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
- }
复制代码 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
这句话很重要,是个阀值。超过这个阀值就会执行执行这句语句容量*加载因子,容量的默认是16,这个也可以自己设定初始值,自己设定的初始值要扩容还是容量*加载因子,加载因子还是0.75,因子不会变,根据容量来走。- /**
- * Adds a new entry with the specified key, value and hash code to
- * the specified bucket. It is the responsibility of this
- * method to resize the table if appropriate.
- *
- * Subclass overrides this to alter the behavior of put method.
- */
- void addEntry(int hash, K key, V value, int bucketIndex) {
- if ((size >= threshold) && (null != table[bucketIndex])) {
- resize(2 * table.length);
- hash = (null != key) ? hash(key) : 0;
- bucketIndex = indexFor(hash, table.length);
- }
- createEntry(hash, key, value, bucketIndex);
- }
复制代码 还有这个方法,resize(2 * table.length);数组扩大为原来的2倍。会比较消耗性能,由于是数组方面的增加容量的一个方法,所有性能跟内存消耗会有点大,最好是有个大概值来设定好初始值会比较好。 |