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 want 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:

  1. User|name
  2. processor|1|speed
  3. processor|1!name
  4. processor|2|speed
  5. disk|1|name
  6. 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
  • Disk
    • 1
      • name = whatever the user inputs
    • 2
      • name = whatever the user inputs

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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *