Maps & HashMaps
If you have ever programmed before you may have heard of something called a dictionary. A map and a dictionary are precisely the same thing. Note that a HashMap is simply an implementation of a map (there are others as well).
A map can be defined simply as a key value pair. They work in a similar way to an array in the sense that a certain object/value can point to another. In the case of an array an int known as an index points to a certain element in the array. For maps any object can point to another. We call the object that we use to access another the key and the object it points to a value. We use keys to access values and our keys can be anything that we want.
It is important to note that our like sets our map has no order. This also means that the following operations are instant: add, remove or find.
To create a map we do the following.
Adding Key-Value Pairs
As mentioned above the elements in our map are known as key-value pairs.
To create a new key-value pair we use .put()
If we attempt to add a key that already exists we will override that key with the new value.
When we want to access a value in our map we must use the key. We can use .get(key) to retrieve a value from our map.
To check if a key exists in a map we can use .containsKey(). Same goes for a value .containsValue().
Finally we can use .clear() to clear a map and .isEmpty() to check if a map is empty.
Different Kind of Maps
Like lists and sets Java has different kinds of maps. They are the following:
To find out more about different kinds of maps click here.