views:

380

answers:

5

According to the HashSet javadoc, HashSet.contains only returns a boolean. How can I "find" an object in a hashSet and modify it (it's not a primitive data type)?

I see that HashTable has a get() method, but I would prefer to use the set.

+2  A: 

You can remove an element and add a different one.

Modifying an object while it is in a hash set is a recipe for disaster (if the modification changes the hash value or equality behavior).

starblue
This is not totally true. It's safe to modify a HashSet element if the change doesn't impact the object's equality (and hash code). For example, if equals and hashCode were not overridden, then the change is safe to do as its equality is not changed.
Steve Kuo
Yes, and that's why I wrote the part in parentheses.
starblue
+1  A: 

You can iterate through the set to find your object.

A word of warning from the API doc though:

"Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set."

Péter Török
"You can iterate ..." but of course if you do that, updating a set element becomes an `O(N)` operation.
Stephen C
+2  A: 

To quote the source of the stock Sun java.util.HashSet:

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

So you are paying for a map, you might as well use it.

bmargulies
I think you are trying to say "use a HashMap" ... correct? :-)
Stephen C
Yes. Sorry, sometimes I can't resist the urge to make little puzzles out of answers.
bmargulies
A: 
Object oldobj; //object to modify
if (hashset.remove(oldobj)) {
   Object newobj; //modified object
   hashset.add(newobj);
}
splix
A: 

Something like:

MyObject obj = new MyObject();
HashSet hashSet = new HashSet();
hashSet.add(obj);

if (hashSet.contains(obj) == true) {
    hashSet.remove(obj);
    obj.setSomething();
    hashSet.add(obj);
}
kovica
1. `== true` - is unnecessary2. you hasn't checked return value of `.remove(obj)`3. `.contains()` is unnecessary if you removing at next step
splix
Despide the fact that all is true, you shouldn't be so picky :)
kovica