Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find and return objects in java hashset

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.

like image 993
user276712 Avatar asked Feb 20 '10 21:02

user276712


3 Answers

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).

like image 132
starblue Avatar answered Oct 24 '22 05:10

starblue


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.

like image 29
bmargulies Avatar answered Oct 24 '22 06:10

bmargulies


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."

like image 2
Péter Török Avatar answered Oct 24 '22 06:10

Péter Török