简体   繁体   English

表格的哈希表- <key, hash table> 在Java中

[英]Hash table of form - <key, hash table> in Java

I just want to know if it is possible to create a hashtable in java of the form <key, hash table> . 我只想知道是否有可能在Java中创建<key, hash table>形式的<key, hash table>

Essentially the first key leads me to a new hash table; 本质上,第一个键将我引导到一个新的哈希表; then I search that table using another key. 然后我使用另一个关键字搜索该表。

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". 其中K1是“哈希表”的键,而K2V是内部“哈希表”的键和值类型。

edit : as @AndreiBodnarescu rightly points out, you must also choose your Map implementation carefully ( Map is an interface). 编辑 :正如@AndreiBodnarescu正确指出的那样,您还必须仔细选择Map实现( Map是一个接口)。 Ask yourself the following questions: 问自己以下问题:

  • is multithreading access required on the outer/inner map? 外部/内部映射上需要多线程访问吗? If yes, consider Hashtable or Collections.synchronizedMap(...) ; 如果是,请考虑HashtableCollections.synchronizedMap(...) ;
  • does insertion order matter? 插入顺序重要吗? If yes, consider LinkedHashMap ; 如果是,请考虑LinkedHashMap ;
  • do you want keys to be sorted? 您想对按键进行排序吗? If yes, consider TreeMap . 如果是,请考虑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 显然InnerValueType仍然可以是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. 如果您的数据结构没有被多个线程访问,则可以使用HashMap替换Hashtable,它具有哈希表结构的所有行为,但没有同步。

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). 您应该使用HashMap ,而不是Hashtable (因为Hashtable是一个遗留集合类,自Java 1.2开始已被HashMap取代)。

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>());

尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM