This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap

 
mike proger
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can you update a object in a hashmap. Lets say the object has a name, account number, and account balance. How would I update the balance for the object in the hashmap.
 
Hentay Duke
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you'll have to get object out of the hashmap to update it and then reinsert back in the hashmap.
 
mike proger
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so basically remove the object from the hashMap and put another another object in the hashmap replacing the old one with the update information?
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, you don't have to remove it at all. You don't even have to get it from the HashMap. If you maintain a reference to it, you can just change it. But, if you don't have a reference and you just have the key, you retrieve the object and change it. There's no need to re-insert it.
 
Hentay Duke
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose I was a bit hasty in my reply earlier.

When in doubt always go with the 'Pres'.

Thanks for correcting me James I'm happy to learn something today. In the project I work on here at my job we use a lot of LinkedLists and it's been a while since I've reviewed all of the different types of collections, maybe it's time I do.
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, it's not a HashMap-specific thing. To modify an object in a collection, you can just modify the object itself. However, if you're dealing with a special type of collection, such as an ordered collection, you have to be careful. The collection won't know to re-order itself if you make changes on it behind the scenes. Likewise, if you change the object you use as a key of a map, it can really mess things up (suppose your changes alter the hashCode() value). So, if you need to do that, it's best to remove first, then change, then re-insert.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic