如何在java hashset中查找和返回对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2303875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to find and return objects in java hashset
提问by user276712
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)?
根据 HashSet javadoc,HashSet.contains 只返回一个布尔值。如何在 hashSet 中“找到”一个对象并修改它(它不是原始数据类型)?
I see that HashTable has a get() method, but I would prefer to use the set.
我看到 HashTable 有一个 get() 方法,但我更喜欢使用该集合。
采纳答案by starblue
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).
在散列集中修改对象是灾难的秘诀(如果修改更改了散列值或相等行为)。
回答by Péter T?r?k
You can iterate through the set to find your object.
您可以遍历该集合以找到您的对象。
A word of warning from the API docthough:
尽管如此,API 文档中有一句警告:
"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."
"注意:如果将可变对象用作集合元素,则必须非常小心。如果对象的值以影响等于比较的方式更改,而对象是集合中的元素,则不会指定集合的行为。 ”
回答by bmargulies
To quote the source of the stock Sun java.util.HashSet:
引用 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.
因此,您正在为地图付费,您不妨使用它。
回答by Igor Artamonov
Object oldobj; //object to modify
if (hashset.remove(oldobj)) {
Object newobj; //modified object
hashset.add(newobj);
}
回答by kovica
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);
}
回答by ccol002
I encountered the same problem and came up with the following solution (it should implement the Set interface but not all methods are here)
我遇到了同样的问题,想出了以下解决方案(它应该实现 Set 接口,但不是所有方法都在这里)
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);
}
}