Java .

Java HashMaps

java.util.HashMap

the HashMap constructors

HashMap hashMapName = new HashMap();

HashMap hashMapName = new HashMap(5); //The 5 sets the initial element capcaity.

HashMap hashMapName = new HashMap(5, .9); //The 5 sets the initial element capcaity. //The .9 is the load factor. // The default load factor is .75.

HashMap hashMapName = new HashMap(mapIn); //creates a new HashMap with the elements of a map.

HashMap methods to find out what is in the HashMap

int HashMapSize = hashMapName.size();

boolean isHashMapEmpty = hashMapName.isEmpty();

boolean isObjectKeyInHashMap = hashMapName.containsKey(objectToSearchForAsKey);

boolean isObjectValueInHashMap = hashMapName.containsValue(objectToSearchForAsValue);

HashMap methods to retrieve elements from the HashMap

Object objectName = 
  (ClassTypeToCastTo) hashMapName.get(keyToGetObjectValueFor);
  //note: Objects coming out of HashMaps have lost 
  //  their class type, and must be cast

Set setOfAllKeys = hashMapName.keySet(); //The set is a "view", // so changes to the original HashMap change the view, // and changes to the view change the original HashMap.

Collection collectionOfAllValues = hashMapName.values(); //The collection is a "view", // so changes to the original HashMap change the view, // and changes to the view change the original HashMap.

Set setOfAllEntryValues = hashMapName.entrySet(); //note: "Returns a collection view of the mappings // contained in this map" // (Platform API Spec, See online refs) //The collection is a "view", // so changes to the original HashMap change the view, // and changes to the view change the original HashMap.

Object cloneOfHashMap = hashMapName.clone(); //Shallow copy of HashMap, // objects in HashMap are not cloned.

HashMap methods to alter what is in the HashMap

Object objectReplacedForKey = 
  hashMapName.put(objectKey, objectToAdd);
  //inserts object value for a specified key
  //returns the object that is replaced for that key, 
  //  null if nothing is repplaced

hashMapName.putAll(mapToAdd); //adds a map into the HashMap

hashMapName.remove(keyObject); //removes a key and value pair for a key

hashMapName.clear();

References


online
The Java 2 Platform Specification
Books
Thinking in Java by Bruce Eckel
Core Java (TM) 2 Volume 1 - Fundamentals by Cay Horstmann and Gary Cornell
Comments
Sign in to be the first to comment on Java HashMaps.