Pages

July 27, 2012

Flattening Hierarchical Data

Posted by Jeremy Mitchell
I'm not a big fan of hierarchical data structures. They can be a pain. For example, I hate having to perform recursive loops to find matching elements.

Unfortunately, many UI controls require hierarchical data (i.e. the Tree component) and sometimes it is unavoidable.

Therefore, if hierarchical data is required, I like to "flatten" the hierarchical data and maintain two data structures - a hierarchical one and a flat one. Flat data structures are much easier to navigate and thanks to the power of object references, each data structure contains references to the same objects so updating an object in the flat data structure also updates it in the hierarchical data structure.

To demonstrate, imagine we have a hierarchical data structure that looks like this:

- Object A
-- Object B
--- Object C

We can use that hierarchical data structure for the Tree component, but, to make our lives easier, let's create a flat data structure (i.e. Array or ArrayCollection) to hold the same objects:

- Object A
- Object B
- Object C

Searching and updating objects in the flat data structure will prove to be much easier.

Here's a example to demonstrate this technique. View source is enabled.

1 comment:

Don Kerr said...

Very helpful Jeremy. Thank you!