开发者

DataStructure for implementing something like nested Maps?

开发者 https://www.devze.com 2023-03-22 11:56 出处:网络
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:

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:

  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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消