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:

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:

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:

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.







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">