This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes HashMap and its cousins Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashMap and its cousins" Watch "HashMap and its cousins" New topic

HashMap and its cousins

Bill Denniston

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

Joined: Oct 14, 2005
Posts: 19751

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: 2367
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.

I agree. Here's the link:
subject: HashMap and its cousins
It's not a secret anymore!