Re: Indexing by multiple keys
markspace wrote:
You can put the same object in more than once, with different keys. This
is a little less safe in terms of programmer usage, but works fine.
class Person {
int ssn;
A Social Security Number is a string, not an int. Were you to foolishly
represent it as a numeric type, an int wouldn't hold the range of values.
String name = "";
}
HashMap<Object,Person> map = new HashMap<Object,Person>();
Say, rather,
Map <String, Person> map = new HashMap <String, Person> ();
Person person = new Person();
map.put( person.ssn, person );
map.put( person.name, person );
Now "person" is in the map twice, once under SSN and once by their name.
As Arne said, this is done by reference so there's no wasted space or
extra copies or anything bad like that.
There could be wasted space. Using your example:
map.put( person.name, person );
map.put( new String( person.name ), person );
will create two instances of name strings with the same value, neither of
which can be GCed while the person lives and is in the map.
I also fear it will create two entries in the map. While 'equals()' is
polymorphic, it also has to handle comparing String to Integer.
--
Lew