Name

HashMap<K,V>

Synopsis

This class implements the Map interface using an internal hashtable. It supports all optional Map methods, allows key and value objects of any types, and allows null to be used as a key or a value. Because HashMap is based on a hashtable data structure, the get( ) and put( ) methods are very efficient. HashMap is much like the Hashtable class, except that the HashMap methods are not synchronized (and are therefore faster), and HashMap allows null to be used as a key or a value. If you are working in a multithreaded environment, or if compatibility with previous versions of Java is a concern, use Hashtable. Otherwise, use HashMap.

If you know in advance approximately how many mappings a HashMap will contain, you can improve efficiency by specifying initialCapacity when you call the HashMap( ) constructor. The initialCapacity argument times the loadFactor argument should be greater than the number of mappings the HashMap will contain. A good value for loadFactor is 0.75; this is also the default value. See Map for details on the methods of HashMap. See also TreeMap and HashSet.

java.util.HashMap<K,V>

Figure 16-24. java.util.HashMap<K,V>

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
// Public Constructors
     public HashMap( );  
     public HashMap(int initialCapacity);  
     public HashMap(Map<? extends K,? extends V> m);  
     public HashMap(int initialCapacity ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.