This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashMap" Watch "HashMap" New topic
Author

HashMap

mike proger
Greenhorn

Joined: Apr 22, 2005
Posts: 14
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

Joined: Oct 27, 2004
Posts: 198
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

Joined: Apr 22, 2005
Posts: 14
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

Joined: Feb 20, 2001
Posts: 580
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.


James Carman, President<br />Carman Consulting, Inc.
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
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

Joined: Feb 20, 2001
Posts: 580
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashMap
 
Similar Threads
Having troubles with a complex program, need help with an illegal start of type error.
Objects and Classes
An easy class/object/importation question.
How comes the inconsistence ?
Thread question