Java Reference
In-Depth Information
Hashtable<String, ErrorMsg> errorMsgsTable = new Hashtable<String, ErrorMsg>
(20);
HashMap<String, ErrorMsg> errorMsgsMap = new HashMap<String, ErrorMsg> (50);
To add elements to the Hashtable or HashMap , use the put() method. The put()
method takes two arguments, both of which are objects. The first argument is the
key and the second is the value or the object you wish to retrieve with the key.
// Create some objects.
ErrorMsg myErrorMsg = new ErrorMsg ();
ErrorMsg myotherErrorMsg = new ErrorMsg ("Some Text");
ErrorMsg mythirdErrorMsg = new ErrorMsg ("Third One");
// Place them in the HashMap.
errorMsgsMap.put ("error one", myErrorMsg);
errorMsgsMap.put ("error two", myotherErrorMsg);
errorMsgsMap put ("error three", mythirdErrorMsg);
// Place them in the Hashtable.
errorMsgsTable.put ("error one", myErrorMsg);
errorMsgsTable.put ( "error two", myotherErrorMsg);
errorMsgsTable.put ( "error three", mythirdErrorMsg);
Now the Hashtable and HashMap have a size of three. You retrieve the values
from the Hashtable or HashMap using the get() method.
// Get them from the HashMap.
ErrorMsg myErrorMsg = (ErrorMsg ) errorMsgsMap.get ("error one");
myErrorMsg = errorMsgsMap.get ("error two");
myErrorMsg = errorMsgsMap.get ("error three");
// Get them from the Hashtable.
myErrorMsg = errorMsgsTable.get ("error one");
myErrorMsg = errorMsgsTable.get ( "error two");
myErrorMsg = errorMsgsTable.get ( "error three");
O THER C OLLECTIONS
Java provides some other collection types that are quite useful in particular situations.
HashSet: A general-purpose yet efficient implementation of the basic Set inter-
face. Elements in a HashSet are not ordered in any particular way, but iteration
(that is, sequential access) to these elements is optimized compared to TreeSets .
Search WWH ::




Custom Search