One of my favorite of all the Collections classes of Java is the HashMap. Its easy to use and easy to understand. HashMap is actually a hash table implementation of the Map interface. The HashMap class is equivalent of HashTable only that the HashMap allows null values and keys. Moreover hashmap is unsynchronized compared to HashTable. Since this is a lot faster because it is not synchronized however it would not be thread safe.

In dealing with this class, always remember that the order of elements is changing over time. In other words the placement of element on this pool of objects is dispersed.

Now that we have described the HashMap let’s take a look on a simple example.

Basic Example of HashMap

The above example will yield on the following result


The above example is very simple though the following lessons has been learned:

  • How to instantiate a hashmap. Specifying the type of key value pair
  • Its also been shown how to add elements on the hashmap using the put method.
  • The get() method were used to access the corresponding value of the specified key argument.

Now that we have know the basics of dealing with HashMap, lets try a more concrete example

HashMap of Objects

This example deals with the use of hashmap in storing of objects. There are a lot of things that happen to this example but to give you an overview here’s what it have.

  • Create a Student class which takes a string on its constructor.
  • The constructor must able to parse the string into tokens and assign it using the setters and getters of the Student class.
  • On the main Class create a init() method that instantiate objects of Students by calling its constructors
  • The init method should be able to return a HashMap with id as the key in getting Student values.
  • Print all the id number on the hashmap and then the student age with respect to the id number.

With the above requirements, please try to create the implementation and compare below for my solution

Here is the Student Class