简体   繁体   中英

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

I have a set of elements with unique ids.

I want to order them somehow, so given an element id I return its previous and next element effectively.

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.

how would you implement it in java?

btw, should I use hashMap/hashtable or 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.

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. I also recommend reading the sourcecode for java.util.HashMap and taking hints from the way they do their hashing etc.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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