From: Boris Punk on
Hi

Could someone tell me what determines the order of the keys in a hashtable?


From: Patricia Shanahan on
On 7/16/2010 11:55 PM, Boris Punk wrote:
> Hi
>
> Could someone tell me what determines the order of the keys in a hashtable?
>
>

Nothing you can rely on, unless you use a LinkedHashMap. The order can
even change due to rehashing when a new item is added.

A hash table divides items up into a number of buckets, using the key's
hash code to select a bucket. A search only looks at the items in the
bucket corresponding to the hash code of the key. The iteration order
depends on the current assignment of keys to buckets.

Patricia
From: Kevin McMurtrie on
In article <1uc0o.87059$hS4.7243(a)newsfe26.ams2>,
"Boris Punk" <khgfhf(a)hmjggg.com> wrote:

> Hi
>
> Could someone tell me what determines the order of the keys in a hashtable?

If the JavaDoc doesn't state an order then it's a mix of JVM version,
initial table size, insertion order, and _lots_ of bit hashing. After
all, a hashing algorithm works best when it eliminates bucket mapping
patterns.

Use something like LinkedHashMap or TreeMap if order matters.
--
I won't see Google Groups replies because I must filter them as spam
From: Lew on
Boris Punk wrote:
>> Could someone tell me what determines the order of the keys in a hashtable?

Kevin McMurtrie wrote:
> If the JavaDoc doesn't state an order then it's a mix of JVM version,
> initial table size, insertion order, and _lots_ of bit hashing. After
> all, a hashing algorithm works best when it eliminates bucket mapping
> patterns.
>
> Use something like LinkedHashMap or TreeMap if order matters.

And don't use 'java.util.Hashtable' even when order doesn't matter. It's been
out of date since '98.

--
Lew
From: markspace on
Boris Punk wrote:
> Hi
>
> Could someone tell me what determines the order of the keys in a hashtable?


Hash tables work by distributing their keys randomly, and therefore
presumably evenly, in an array. The hash code and the hashing algorithm
that uses the hash code are basically random number generators that
produce indexes into this array.

So the order of the keys is random, and as Patricia pointed out will
change at runtime if the array needs to be re-hashed.