how do i have direct access to a key position in a hashtable ?
index access a hashtable
Page 1 of 18 Replies - 2896 Views - Last Post: 20 January 2011 - 05:03 AM
Replies To: index access a hashtable
#2
Re: index access a hashtable
Posted 20 January 2011 - 12:18 AM
You don't. You use the actual key.
#3 Guest_hasher*
Re: index access a hashtable
Posted 20 January 2011 - 12:31 AM
i know there is a way to sequentially access elements. (Enumeration.) But i think there should be a way of directly accessing elements.
#4 Guest_hasher*
Re: index access a hashtable
Posted 20 January 2011 - 12:32 AM
i know there is a way to sequentially access elements. (Enumeration.) But i think there should be a way of directly accessing elements.
#5
Re: index access a hashtable
Posted 20 January 2011 - 12:54 AM
uhm get(key)? see the API docs.
#6
Re: index access a hashtable
Posted 20 January 2011 - 02:07 AM
As masijade says, get(key) is the direct way to access the elements.
If this isn't fulfilling your needs maybe you could describe the task you are trying to solve. Gaining access the the Hashtable's underlying array is unlikely to be a good solution so understanding your task would help us suggest a different one.
If this isn't fulfilling your needs maybe you could describe the task you are trying to solve. Gaining access the the Hashtable's underlying array is unlikely to be a good solution so understanding your task would help us suggest a different one.
#7 Guest_hasher*
Re: index access a hashtable
Posted 20 January 2011 - 02:32 AM
i need to randomly select a key.
#8
Re: index access a hashtable
Posted 20 January 2011 - 02:33 AM
So get the keyset as a set, call toArray on that, and pull keys out of that array.
#9
Re: index access a hashtable
Posted 20 January 2011 - 05:03 AM
I'd go with the keySet() technique too. If the toArray bothers you, use an iterator to get to the generated index:
If it seems wasteful using the keySet technique, try it out and see if it really is slow. If you find it too slow after testing, consider keeping an ArrayList of keys separately. Best to avoid this though. This is where it becomes easy to introduce bugs.
int requiredIndex = /*someRandomNumber*/;
assert requiredIndex < map.size();
Set<K> keys = map.keySet();
Iterator<K> = it = keys.iterator();
for(int i = 0; i < requuiredIndex; i++) {
it.next();
}
K randomKey = it.next();
If it seems wasteful using the keySet technique, try it out and see if it really is slow. If you find it too slow after testing, consider keeping an ArrayList of keys separately. Best to avoid this though. This is where it becomes easy to introduce bugs.
Page 1 of 1

New Topic/Question
Reply
MultiQuote






|