| Author |
HashMap and its cousins
|
Bill Denniston
Greenhorn
Joined: Feb 18, 2006
Posts: 5
|
|
|
I have what I think should be some kind of collection of objects. I want to be able to quickly search the collection and retrieve a member object that has a given (string) value in a particular field. I thought that HashMap would be the right collection type. However, I have not been able to get a HashMap to accept a value that is other than a primitive; I can't get it to accept my object as the value with the key being the (string) value of a particular field in the object. (I have found lots of examples of this simple case, where the key is a string and the value is some other primitive, like an integer or another string, but not where the value is an object.) I also have not been able to create a HashMap that is typed to a generic of my object (e.g. HashMap<MyObject> hash = new HashMap<MyObject>(), which works great with an ArrayList. Any help, suggestions or references to examples would be appreciated. Thanks.
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
Apparently you are using Java 5, so it's okay (and even preferable) to use generics. It's quite simple:I'm surprised you only found examples with primitives, since before Java 5 it was very hard to use Maps with primitives, and easy with Objects. You had to box the ints into Integers and so on.
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
I think you have some confusion on what a primitive type is. The primitives are boolean, byte, char, short, int, long, float, and double. All other types are objects. Here is an example of using a HashMap with objects as keys.
|
 |
 |
|
|
subject: HashMap and its cousins
|
|
|