Comp 110 Map

Map is a standard Java interface for an Abstract Data Type used to represent a mapping of entries between Keys and Values. Every Key maps to a specific Value.

HashMap is an implementation of the Map interface.

Maps hold objects at certain key locations and the type of object it can hold is specified during the declaration and construction of a Map. The type of Key and Value of a Map has is specified within the <diamond syntax>.

In order to use a Map in your programs, you must import it first because Map is defined in the java.util package:

import java.util.Map; // Interface
import java.util.HashMap; // Implementation

Here is how one is declared and constructed:

Map<KeyType, ValueType> variable = new HashMap<KeyType, ValueType>();

Here is an example of a HashMap being constructed with the Key as a String and the Value as an Integer. Keys and Values can be almost any type.

Map<String, Integer> people = new HashMap<String, Integer>();

Like an List, Maps can be thought of as an array. However instead of storing values at a certain index like in arrays, we store values at a certain Key.  In arrays we reference values in an array like this:

int[] arr = new int[3]; 
arr[0] = 4;
arr[1] = 5;
arr[2] = 6;
System.out.println(arr[0]); //prints out 4

However in Maps, we store them like this: 

Map<String, Integer> people = new HashMap<String, Integer>();
people.put("John", 42);
people.put("Jeffrey", 36);
people.put("Sarah", 19);
System.out.println(people.get("John")); //Prints 42
people.put("John", 24);
System.out.println(people.get("John")); //Prints 24

There are many methods listed in the documentation, but in COMP110 we will mostly focus on size, put, get, and  containsKey.


int size()

Calling Map's size method will return to you the number of elements it contains. 


void put(<Key> nameOfKey, <Value> nameOfValue)

You can put elements to a Map by calling the put method. The item to be added is passed as an argument along with its Key. Its type must match the type the Map was declared to hold. This will add items into the Map at the specific Key. 


<Value> get(<Key> nameOfKey)

You can get an item stored in the Map by calling the get method with a the parameter corresponding to the Key of the Value you want to retrieve. If you try to get a value with a key that does not exist, you will be greeted with a null value as a result. 


boolean containsKey(<Key> nameOfKey)

The contains key method returns a boolean value, true or false. It returns true if the value you provided it is listed in the Map as an existing key. Otherwise, it is false.