简体   繁体   English

如何实现hashTable作为Java中链表的索引器?

[英]how to implement hashTable as an indexer to linked-list in java?

I have a set of elements with unique ids. 我有一组具有唯一ID的元素。

I want to order them somehow, so given an element id I return its previous and next element effectively. 我想以某种方式对它们进行排序,因此给定一个元素ID,我可以有效地返回其上一个和下一个元素。

If I would implement it in any language with pointers I would have created a hashTable with and each node in the doublely linked list will point to the previous and next element respectively. 如果我用指针用任何语言实现它,我都会用创建一个hashTable,并且双向链接列表中的每个节点将分别指向上一个和下一个元素。

how would you implement it in java? 您将如何在Java中实现它?

btw, should I use hashMap/hashtable or hashSet? 顺便说一句,我应该使用hashMap / hashtable还是hashSet?

If you want to actually use a doubly linked list view over a hash table, the best way to do so is to implement it yourself. 如果要在散列表上实际使用双向链表视图,最好的方法是自己实现。 Each node knows the value of its content, the next element in the bucket (singly linked buckets are easy), and the previous/next elements in the doubly linked list. 每个节点都知道其内容的值,存储桶中的下一个元素(单链接的存储桶很容易)以及双链接列表中的上一个/下一个元素。 You are then free to implement ListIterator providers and weird Deque implementations as much as you like. 然后,您可以随意实现ListIterator提供程序和怪异的Deque实现。

It's a little bit like reinventing the wheel honestly, but there are no standard hash implementations that also provide truly useful access to the linked list outside their iterator. 这有点像诚实地重新发明轮子,但是没有标准的哈希实现也可以提供对迭代器外部的链表的真正有用的访问。

See this class that I wrote ; 我写的这门课 ; it's a Set not a Map , and it has some extra fancy stuff in it (for the purposes of getting a random element instead of the most recent or last-added), but it should give you some ideas. 它是一个Set而不是Map ,并且其中包含一些额外的奇特的东西(目的是为了获取随机元素而不是最近添加或最后添加的元素),但是它应该给您一些想法。 I also recommend reading the sourcecode for java.util.HashMap and taking hints from the way they do their hashing etc. 我还建议阅读java.util.HashMap的源代码,并从其进行哈希处理的方式java.util.HashMap获取提示。

Keep in mind: If you want to maintain an actual sorted set, hash tables are not what you should be using. 请记住:如果要维护实际的排序集,则不应该使用哈希表。 If you need it to be always sorted, get a sorted tree set; 如果需要始终对其进行排序,请获取已排序的树集; those are also quite traversable. 这些也很容易遍历。

Edit: Included the link to the class because I'm bad and I forgot 编辑:因为我很糟糕并且忘记了,所以包含了指向课程的链接

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

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