1

I just want to know if it is possible to create a hashtable in java of the form <key, hash table>.

Essentially the first key leads me to a new hash table; then I search that table using another key.

4 Answers 4

10

Sure it is:

Map<K1, Map<K2, V>> themap = new HashMap<K1, Map<K2, V>>();

where K1 is the key of the "hash table", and K2 and V are the key and value type of the inner "hash table".

edit: as @AndreiBodnarescu rightly points out, you must also choose your Map implementation carefully (Map is an interface). Ask yourself the following questions:

  • is multithreading access required on the outer/inner map? If yes, consider Hashtable or Collections.synchronizedMap(...);
  • does insertion order matter? If yes, consider LinkedHashMap;
  • do you want keys to be sorted? If yes, consider TreeMap.

Choose your implementation carefully!

Sign up to request clarification or add additional context in comments.

Comments

2

you can use

Hashtable<KeyType,Hashtable<InnerKeyType,InnerValueType>> ht = new Hashtable<>();

where obviouslly the InnerValueType can still be a Hashtable

If your data structure is not accessed by multiple threads, you can repalce Hashtable with HashMap which has all the behaviour of a hashtable structure but without the synchronisation.

Comments

1

Ofcourse that's possible. You should use HashMap, not Hashtable (because Hashtable is a legacy collection class that has been replaced by HashMap since Java 1.2).

Example:

Map<String, Map<String, Object>> mapOfMaps = new HashMap<String, Map<String, Object>>();

mapOfMaps.put("one", new HashMap<String, Object>());
mapOfMaps.put("two", new HashMap<String, Object>());

Comments

0

try

Hashtable<Integer, Hashtable> hashTable = new Hashtable<Integer, Hashtable>():

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.