This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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.
Joined: Oct 27, 2004
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.
Joined: Feb 20, 2001
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.