Re: HashMap.put error in Xcode
Composer wrote:
Humble apologies to all.
I didn't look closely enough at the HashMap.put() documentation. Of
course you're right; it takes two Objects. I had misinterpreted what
my 1999 Sams book said: "Any class that defines a hashCode() method
can be efficiently stored and accessed in a hash table." Since the
hashCode() methods of BitSet and String return an int, I assumed that
an int would be suitable as a key in a HashMap. I was wrong.
(Why do these classes have a hashCode() method, if it doesn't create a
unique key?)
The point of hash-based data structures is to partition the keys, based
on a hash code, so that only a subset of the keys in the data structure
need to be searched for any given access.
To answer why I was using a HashMap in the first place, I expect the
user to generate a large number of 12-bit BitSets. I want to do 2
things with them: de-duplicate them before adding them to a list,
then draw certain subsets from the list based on certain bits in each
BitSet being on or off. It seemed that a BitSet, with its and() and
or() methods, would support the second objective, and storing the
BitSets in a HashMap would allow easy de-duplication and speedy
searching.
If it's true that the hashCode() method won't reliably give me a
unique key for each BitSet, then I could create my own; maybe a short
(16 bit) number could be created in which the first 12 bits are
significant. But maybe I should abandon the whole idea of hash codes
and keys, and simply put all my BitSets into a Vector, which I would
search manually using the BitSet.equals() method.
I still don't see why you cannot use a HashMap with BitSet keys. It is
VERY unlikely that your BitSet instances all have the same hash code,
and that is what it would take to make a HashMap access as inefficient
as a linear search of a Vector.
Or use a HashSet of BitSet elements.
You could probably do the task more efficiently using short, if you
designed your data structures carefully, but it would be more work.
Patricia