initCapacity: 16
loadFactor: 0.75
resize: double
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30; //1073741824
if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
HashMap is under package java.util
,the annotations of it are below:
Firstly, Hash table based implementation of the Map interface.
Secondly, this implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Thirdly, an instance of HashMap has two parameters that affect its performance:
Fourthly, as a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.
Fifthly, if many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. * Note that usingmany keys with the same {@code hashCode()} is a sure way to slow down performance of any hash table. * To ameliorate impact, when keys are {@link Comparable}, this class may use comparison order among keys to help break ties.
Sixthly, note that this implementation is not synchronized.
Map m = Collections.synchronizedMap(new HashMap(...));
Seventhly, The iterators returned by all of this class's "collection view methods" are fail-fast:
At the end, note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in thepresence of unsynchronized concurrent modification.
initCapacity: 11
loadFactor: 0.75
resize: double add one
public Hashtable() {
this(11, 0.75f);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
int newCapacity = (oldCapacity << 1) + 1;
Hashtable implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value.
Firstly, To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode
method and the equals
method.
An instance of Hashtable
has two parameters that affect its performance: initial capacity and load factor.
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
Note that the hash table is open: in the case of a “hashcollision”, a single bucket stores multiple entries, which must be searchedsequentially.
The load factor is a measure of how full the hashtable is allowed to get before its capacity is automatically increased.
The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.
Generally, the default load factor (.75) offers a good tradeoff betweentime and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).
The initial capacity controls a tradeoff between wasted space and theneed for rehash
operations, which are time-consuming.No rehash
operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor.
However, setting the initial capacity too high can waste space.
If many entries are to be made into a Hashtable
, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.
This example creates a hashtable of numbers. It uses the names of the numbers as keys:
Hashtable numbers
= new Hashtable();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);}
{
Integer n = numbers.get("two");
if (n != null) {
System.out.println("two = " + n);
}}
Secondly, The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast:
Thirdly, note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. * Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
As of the Java 2 platform v1.2, this class was retrofitted to
ConcurrentHashMap is under package java.util.concurrent
.
It is a hash table supporting full concurrency of retrievals and high expected concurrency for updates.
Firstly, Retrieval operations (including {@code get}) generally do not block, so may overlap with update operations (including {@code put} and {@code remove}). Retrievals reflect the results of the most recently completed update operations holding upon their onset.
Secondly, the table is dynamically expanded when there are too many collisions (i.e., keys that have distinct hash codes but fall into the same slot modulo the table size), with the expected average effect of maintaining roughly two bins per mapping (corresponding to a 0.75 load factor threshold for resizing).
Thirdly, a {@link Set} projection of a ConcurrentHashMap may be created (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed (using {@link #keySet(Object)} when only keys are of interest, and themapped values are (perhaps transiently) not used or all take the same mapping value.
Fourthly, A ConcurrentHashMap can be used as scalable frequency map (a form of histogram or multiset) by using {@link java.util.concurrent.atomic.LongAdder} values and initializing via {@link #computeIfAbsent computeIfAbsent}. For example, to add a count to a {@code ConcurrentHashMap
Sixthly, this class and its views and iterators implement all of the optional methods of the {@link Map} and {@link Iterator} interfaces.
Seventhly, like {@link Hashtable} but unlike {@link HashMap}, this class does not allow {@code null} to be used as a key or value.
Eighthly, ConcurrentHashMaps support a set of sequential and parallel bulk operations that, unlike most {@link Stream} methods, are designed to be safely, and often sensibly, applied even with maps that are being concurrently updated by other threads; for example, when computing a snapshot summary of the values in a shared registry.
forEach: Perform a given action on each element.
A variant form applies a given transformation on each element before performing the action.
search: Return the first available non-null result of applying a given function on each element; skipping further search when a result is found.
reduce: Accumulate each element. The supplied reduction function cannot rely on ordering (more formally, it should be both associative and commutative).
There are five variants:
These bulk operations accept a {@code parallelismThreshold} argument. Methods proceed sequentially if the current map size is estimated to be less than the given threshold.
Using a value of {@code Long.MAX_VALUE} suppresses all parallelism. Using a value of {@code 1} results in maximal parallelism by partitioning into enough subtasks to fully utilize the {@link ForkJoinPool#commonPool()} that is used for all parallel computations.
Normally, you would initially choose one of these extreme values, and then measure performance of using in-between values that trade off overhead versus throughput.
Ninetiethly, the concurrency properties of bulk operations follow from those of ConcurrentHashMap: Any non-null result returned from {@code get(key)} and related access methods bears a happens-before relation with the associated insertion or update.
The tenth, search and transformation functions provided as arguments should similarly return null to indicate the lack of any result (in which case it is not used).
The eleventh, methods accepting and/or returning Entry arguments maintain key-value associations. They may be useful for example when finding the key for the greatest value. Note that "plain" Entry arguments can be supplied using {@code newAbstractMap.SimpleEntry(k,v)}.
The twelfth, Bulk operations may complete abruptly, throwing an exception encountered in the application of a supplied function. Bear in mind when handling such exceptions that other concurrently executing functions could also have thrown exceptions, or would have done so if the first exception had not occurred.
Speedups for parallel compared to sequential forms are common but not guaranteed. Parallel operations involving brief functions on small maps may execute more slowly than sequential forms if the underlying work to parallelize the computation is more expensive than the computation itself. Similarly, parallelization may not lead to much actual parallelism if all processors are busy performing unrelated tasks.
All arguments to all task methods must be non-null.
This class is a member of the Java Collections Framework.