• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap and its cousins

 
Bill Denniston
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic