• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Creating a compount HashMap key

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All,

I've been trying to create a compound HashMap key with little success. In particular, my compound map key looks like the following:



It's used to insert data into a May like Map<Key, String> map = new HashMap<Key, String>(). Unforunately, when I go to retrieve the value using something like the following:



I get null instead of the actual value. Does this have something to do with using a String in the hashcode? I'm really lost (and frustrated!).

Thanks,
Dave
[ June 18, 2006: Message edited by: David Irwin ]
 
David Irwin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Found my mistake...bug in the equals method.

Originally posted by David Irwin:
All,


[ June 18, 2006: Message edited by: David Irwin ]

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For future reference, you can save yourself a lot of typing and debugging just by relying on the Java implementations of equals, hashCode and compareTo.
All you're doing is concatenating two strings, so do that once in the constructor, & delegate from then on - saves you a lot of code & extraneous transient string operations.
The equals method needs a couple of checks before you delegate according to the arcane rules of equals methods, but aside from that the key class becomes totally brain dead the way you want it. Another alternative is to bag creating a key class and externalizing the string concatenation, but there may be good reason to encapsulate it here (like if it gets more complex than two strings, or key creation is not well contained in one place.
(Note the below code is a fat-fingered variation on a tested key class, pardon for any typos.)

reply
    Bookmark Topic Watch Topic
  • New Topic