Re: Determine index from array reference?
Knute Johnson wrote:
I'm not sure how it can be faster but without testing it I can't be
sure.
It's faster because lookups into a HashMap are O(1) and lookups into an
ArrayList are O(n) on the size of the collection. Plus you skip the code to
derive an index then use it to do the lookup in the parallel list.
As to memory, a Map with two objects can't use much less memory
than an int and a get method but so what.
It can use less memory when there are two or more lists coordinated in
parallel, which was the condition under which I suggested using a Map would be
worthwhile.
Also how would you find the key with a map?
Given that you were looking up an index with a JTextField as the key, then
using the index to find a SomeOtherThing, you already have the key - the
JTextField - so there is no lookup of the key, only of the SomeOtherThing
associated with the key.
The suggestion of a Map is predicated on the notion that you are doing that
kind of parallel lookup.
How is it going to be less buggy?
By preventing any bugs caused by independent Lists falling out of synchrony
with each other. With two Lists, the orders or lengths might differ. (This
type of thing has been a question on these newsgroups before.) With a Map, if
the key is in there, so is the value (which might be null). No chance of the
order or length differing, hence less opportunity for bugs.
- Lew