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.

Shivan Dragon
15.2k10 gold badges68 silver badges104 bronze badges
asked Jan 18, 2012 at 13:37

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!

answered Jan 18, 2012 at 13:39
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.

answered Jan 18, 2012 at 13:41
0
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>());
answered Jan 18, 2012 at 13:41
0

try

Hashtable<Integer, Hashtable> hashTable = new Hashtable<Integer, Hashtable>():
answered Jan 18, 2012 at 13:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.