Java APIs - HashMaps

Data Structure Indexing Comparison

  • Array (type[], e.g., double[]): Accesses data via an integer index (index→value\text{index} \rightarrow \text{value}).

  • Matrix (type[][], e.g., int[][]): Accesses data via two-dimensional coordinates ((row,col)→value(\text{row}, \text{col}) \rightarrow \text{value}).

  • ArrayList (ArrayList<type>, e.g., ArrayList<String>): Dynamically sized list indexed by integers (index→value\text{index} \rightarrow \text{value}).

  • HashMap (HashMap<KeyType, ValueType>): Associates unique keys of any object type to corresponding values (key→value\text{key} \rightarrow \text{value}).

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); } &nbsp;&nbsp;&nbsp;&nbsp;

  • Ordering: Elements stored in a HashMap are not ordered.