title: Updating an object within a Set
body: <p>Let's say I have this type in my application:</p>
  
  <pre><code>public class A {
    public int id;
    public B b;
  
    public boolean equals(Object another) { return this.id == ((A)another).id; }
    public int hashCode() { return 31 * id; //nice prime number }
  }
  </code></pre>
  
  <p>and a <code>Set<code>&lt;A</code>></code> structure. Now, I have an object of type <code>A</code> and want to do the following:</p>
  
  <ul>
  <li>If my <code>A</code> is within the set, update its field <code>b</code> to match my object.</li>
  <li>Else, add it to the set.</li>
  </ul>
  
  <p>So checking if it is in there is easy enough (<code>contains</code>), and adding to the set is easy too. My question is this: how do I get a handle to update the object within? Interface <code>Set</code> doesn't have a <code>get</code> method, and the best I could think of was to remove the object in the set and add mine. another, even worse, alternative is to traverse the set with an iterator to try and locate the object.</p>
  
  <p>I'll gladly take better suggestions... This includes the efficient use of other data structures.</p>
  
  <p>Yuval =8-)</p>
  
  <p><strong>EDIT</strong>: Thank you all for answering... Unfortunately I can't 'accept' the best answers here, those that suggest using a <code>Map</code>, because changing the type of the collection radically for this purpose only would be a little extreme (this collection is already mapped through Hibernate...)</p>