in reply to What defines the choice of a Hash or an Array?
An array is just a list of things indexed by sequential numbers. A hash is an "associative array"; an unordered list of things indexed by keys that are each associated with one of the things. Just as an array's indices are 'unique' (you can't have two elements names 33, for example), a hash's keys are also unique (you can't have two hash keys both named 'pete'). Hash elements aren't inherently ordered. That means that there isn't any concept of 'pete comes before dave'.
So use an array anytime you need an ordered list, or a list of things indexed numerically starting at zero. Use an array if you need to push, pop, shift, or unshift.
Use a hash anytime you need to organize a bunch of things indexed by keys instead of '0 .. n' subscripts. Use a hash where order is unimportant (or where you don't mind sorting the keys, or maintaining a sorted array of keys). Use a hash if you need to maintain uniqueness of keys. Use a hash for sparse arrays, if it makes sense to do so. Use a hash if you need to quickly verify existance of an item based on its key (exists).
There are an infinite number of uses for each.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What defines the choice of a Hash or an Array?
by ghenry (Vicar) on Mar 31, 2005 at 08:00 UTC |