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
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
orCollections.synchronizedMap(...)
; - does insertion order matter? If yes, consider
LinkedHashMap
; - do you want keys to be sorted? If yes, consider
TreeMap
.
Choose your implementation carefully!
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.
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>());
try
Hashtable<Integer, Hashtable> hashTable = new Hashtable<Integer, Hashtable>():