• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

HashMap and its cousins

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 28346
97
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
reply
    Bookmark Topic Watch Topic
  • New Topic