Philipp Dietl
Philipp Dietl

Reputation: 102

Is a Hashtable as value of another Hashtable recommendable?

I am currently struggling with the concept of having a Hashtable as value in a key-value pair of another Hashtable.

Hashtable<Key,Hashtable<Key,Value> table;

In my current project I require a way to group data 2 times, kinda like a node-structure (treeview). Here's a simple example of the kind of data I want to store:

The only thinks which came to my mind are using the above mentioned Hashtable-construct or creating a "node-collection" which would group my data as explained. (does such a "node-collection" exist in the Java API?)

Is it favorable to use the Hashtable-idea over the node-collection-idea?

Upvotes: 1

Views: 185

Answers (2)

Little Santi
Little Santi

Reputation: 8833

The advantage of generic structures is that they serve for a number of needs out-of-the-box, but its disadvantage is that they have low readability and they lack of semantic. Compare these two declarations:

Hashtable<Key1,Hashtable<Key2,Value2>>

Hashtable<Key,BoughtItemsMap>

That's enough for a two-level grouping structure. So you'd better not even imagine how would it be for a three-level:

Hashtable<Key1,Hashtable<Key2,Hashtable<Key3,Value3>>>

Is it favorable to use the Hashtable-idea over the node-collection-idea?

It depends on your needs: A Hashtable (or better, a Map) is used to map keys to values. A collection, instead, does not map; Just contains values.

So, if the 2nd level of your structure does not need mapping, a Collection should be enough. Something like this:

class MyCollectionOfElements extends ArrayList<Element>{...}

Map<Key, MyCollectionOfElements> map=new HashMap<Key, MyCollectionOfElements>();

Upvotes: 2

jwenting
jwenting

Reputation: 5663

Why shouldn't it be proper? It's a pretty normal way to do things, though as things get more complex you might want to start resorting to designing your own classes to use as data structures.

Upvotes: 3

Related Questions