Java APIs - HashMaps
Data Structure Indexing Comparison
Array (
type[], e.g.,double[]): Accesses data via an integer index ().Matrix (
type[][], e.g.,int[][]): Accesses data via two-dimensional coordinates ().ArrayList (
ArrayList<type>, e.g.,ArrayList<String>): Dynamically sized list indexed by integers ().HashMap (
HashMap<KeyType, ValueType>): Associates unique keys of any object type to corresponding values ().
Java HashMap Core Operations
Instantiation:
Syntax:
HashMap<KeyType, ValueType> myMap = new HashMap<KeyType, ValueType>();Example:
HashMap<String, String> animalSoundMap = new HashMap<String, String>();
Insertion (
put):Associates a key with a value in the map.
Syntax:
myMap.put(key, value);Example:
animalSoundMap.put("dog", "bark");
Retrieval (
get):Returns the value mapped to the given key.
Syntax:
myMap.get(key);Example:
animalSoundMap.get("dog");returns"bark".
Essential Methods and Traversal
size(): Returns the total number of key-value pairs stored (int size = myMap.size();).containsKey(key): Checks whether a specific key exists within the map.remove(key): Removes the mapping associated with the specified key.keySet(): Returns a set of all keys contained in the map.Iteration:
Traverse keys using an enhanced for-loop over
keySet():java for (keyType key : myMap.keySet()) { myMap.get(key); }
Ordering: Elements stored in a
HashMapare not ordered.