|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
