Generics and associative array of keys and diverse objects

F

Frank Fredstone

What is the right way to create a map from Strings to arbitrary and
diverse objects? For example, so I can have:

map.put("a", "text");
map.put("b", new Integer(2));

etc. where the value needs to be able to be any sub-class of Object.


I read in a generics FAQ:

http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

about creating a collection containing objects like Pair<K, ?>, and
presumably I could implement a class that behaves like a Map but uses
a collection of pairs with an unbounded value, but I would think this
would be a pretty common thing and there might be an easier way to do
that. Ideas?
 
?

=?ISO-8859-1?Q?Tobias_Schr=F6er?=

Frank said:
What is the right way to create a map from Strings to arbitrary and
diverse objects? For example, so I can have:

map.put("a", "text");
map.put("b", new Integer(2));

etc. where the value needs to be able to be any sub-class of Object.


I read in a generics FAQ:

http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

about creating a collection containing objects like Pair<K, ?>, and
presumably I could implement a class that behaves like a Map but uses
a collection of pairs with an unbounded value, but I would think this
would be a pretty common thing and there might be an easier way to do
that. Ideas?

How about Map<String, Object> ?
This is applicable, if Object is the least common type your value
objects inherit from. As seen in your example, Object is your choice.

Tobi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,078
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top