Using Generics to Store Specific Type of Objects in a HashMap


This example shows how to use generics to store objects in a HashMap. Before the time of generics,
one could also store specific objects in a Map but it could only be declared to contain Object instances,
without specifying what kind of objects.
And since values in a Map is stored in key / value pairs, the key was also regarded as an Object instance.

The HashMap was then declared like this:


HashMap persons = new HashMap();


Let's say we wanted to store persons in the map with the persons name as the key. Before generics we would have done like this:


Person p = new Person();
p.setName("John", "Wayne");
p.setSalary(150000.00);
p.setTitle("CIO");

persons.put("John", p);

//And to retrieve the value we would have needed an explicit cast

Person john = (Person)persons.get("John");


One of the drawbacks having to cast objects it that it could lead to errors in case trying to cast to another type than the actual one.
With generics we can instead declare of what type both the key and the value should be (i.e. use a typesafe map).
Then we don't have to do any casting between different types:


HashMap<String,Person> persons = new HashMap<String,Person>();

Person p = new Person();
p.setName("John", "Wayne");
p.setSalary(150000.00);
p.setTitle("CIO");

persons.put("John", p);

//And to retrieve the value (without the explicit cast)

Person john = persons.get("John");


By using typesafe maps, you can avoid ClassCastException problems when retrieving items from a map.
This makes your code much more stable and less sensitive to the contents of the map.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: