how to find and return objects in java hashset

点点圈 提交于 2019-12-31 21:30:11

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


Object oldobj; //object to modify
if (hashset.remove(oldobj)) {
   Object newobj; //modified object
   hashset.add(newobj);
}



回答5:


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);
}



回答6:


I encountered the same problem and came up with the following solution (it should implement the Set interface but not all methods are here)

public class MySet<T> implements Set<T>{

    private HashMap<T,T> items = new HashMap<T,T>();


    public boolean contains(Object item) 
    {
        return items.containsKey(item);
    }

    public boolean add(T item) 
    {
        if (items.containsKey(item))
            return false;
        else
        {
            items.put(item, item);
            return true;
        }
    }

    public T get(T item) 
    {
        return items.get(item);
    }
}


来源:https://stackoverflow.com/questions/2303875/how-to-find-and-return-objects-in-java-hashset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!