Java in a Nutshell, 5th Edition [Electronic resources]

نسخه متنی -صفحه : 1191/ 713
نمايش فراداده

HashMap<K,V>java.util

Java 1.2cloneable serializable collection

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.

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 , float

loadFactor ); // Methods Implementing Map public void

clear ( ); public boolean

containsKey (Object

key ); public boolean

containsValue (Object

value ); public Set<Map.Entry<K,V>>

entrySet ( ); public V

get (Object

key ); public boolean

isEmpty ( ); default:true public Set<K>

keySet ( ); public V

put (K

key , V

value ); public void

putAll (Map<? extends K,? extends V>

m ); public V

remove (Object

key ); public int

size ( ); public Collection<V>

values ( ); // Public Methods Overriding AbstractMap public Object

clone ( ); }

Subclasses

LinkedHashMap