DataStructure for implementing something like nested Maps?
I want to have a map that permits a tree-like behaviour. I want to be able to define a Map from string to an object, that can be another map, or a string:
Map<String,(String OR Map)>
The only way I think I know how to do it is through the Visitor Pattern. Is there an already made data structure that implements this?
UPDATE: Here is the context: I wan开发者_JAVA技巧t to parse form submitted through a post request. The form is multilevel and can have an arbitrary number of fields(chosen by the user). What I decided to do is to name the fields in the form with numbers as such:
- User|name
- processor|1|speed
- processor|1!name
- processor|2|speed
- disk|1|name
- disk|2|name
I decided to break it up at | and then create a tree like structure so itwould look something like this:
- User
- name = whatever the user inputs
- Processor
- 1
- speed = whatever the user inputs
- name = whatever the user inputs
- 2
- speed = whatever the user inputs
- 1
- Disk
- 1
- name = whatever the user inputs
- 2
- name = whatever the user inputs
- 1
Only the last leaves would contain strings. There is not that many fields so I had a feeling using a Map may be a bit of an overkill, but honestly I really didn't know how to do this with anything else.
Introduce an object that represents String
or Map
. Presumably you use them in a way that has some shared behaviour? This could be abstracted to a common base class, and it sounds a little like the composite pattern (tree-like behaviour). For example:
interface StructuredObject {}
class Leaf implements StructuredObject {}
class Composite implements StructuredObject {}
Map<String, StructuredObject> map = ...;
As you point out, you can then use the visitor pattern to traverse through the map and avoid type casting.
Most map implementations have values of a specific type. If you want multiple value types you can do this by wrapping a map of your choice, e.g. a TreeMap.
Google Collections has a very nice API MultiMap
for this use case
精彩评论