This discussion is archived
1 Reply Latest reply: May 2, 2012 3:43 PM by EJP RSS

Collection of multiple object types

932136 Newbie
Currently Being Moderated
I have a HahMap of Key Value pairs. The key is string but the value can be a mix of any custom object types for example, Person, Exam or XYZ.

so I create a hashmap like this:
Map<String, Object> myMap= new HashMap<String, Object>();

Person p = new Person();
Exam e = new Exam();
XYZ xy = new XYZ();

myMap.put("p", p);
myMap.put("e", e);
myMap.put("xy", xy);
Now When Loop through the map and get each items like this, I get the warning: unchecked cast
required: Person
found: java.lang.Object
Person p2 = (Person) myMap.get("p");
How to declare the hashmap to avoid the warnings. ?
1) I know I can suppress the warnings, but I don't want to do that.
2)We can avoid the warning, if we add objects of the same type and declare the HashMap like this:
Map<String, Person> myMap= new HashMap<String, Person>();
But my hashmap may contain objects of multiple types.

Please help with sample code.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points