为什么java.util.HashSet没有get(Object o)方法? [英] Why doesn't java.util.HashSet have a get(Object o) method?
问题描述
我已经看到了其他关于根据索引值从 Set
获取对象的问题,我理解为什么这是不可能的。但是我还没有找到一个很好的解释为什么不允许get by object,所以我想问一下。
I've seen other questions about getting objects from Set
's based on index value and I understand why that is not possible. But I haven't been able to find a good explanation for why a get by object is not allowed so thought I would ask.
HashSet
由 HashMap
支持,因此从中获取对象应该非常简单。就像现在一样,我似乎必须遍历 HashSet
中的每个项目,并测试相等性,这似乎是不必要的。
HashSet
is backed by a HashMap
so getting an object from it should be pretty straightforward. As it is now, it appears I would have to iterate over each item in the HashSet
and test for equality which seems unnecessary.
我可以使用 Map
但我不需要一个键:值对,我只需要一个 Set
。
I could just use a Map
but I have no need for a key:value pair, I just need a Set
.
例如说我有 Foo.java
:
package example;
import java.io.Serializable;
public class Foo implements Serializable {
String _id;
String _description;
public Foo(String id){
this._id = id
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
public boolean equals(Object obj) {
//equals code, checks if id's are equal
}
public int hashCode() {
//hash code calculation
}
}
和 Example.java
:
package example;
import java.util.HashSet;
public class Example {
public static void main(String[] args){
HashSet<Foo> set = new HashSet<Foo>();
Foo foo1 = new Foo("1");
foo1.setDescription("Number 1");
set.add(foo1);
set.add(new Foo("2"));
//I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want.
Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed?
System.out.println(theFoo.getDescription); //Should print Number 1
}
}
是因为equals方法是为了测试绝对相等而不是逻辑相等(在这种情况下包含(Object o)
就足够了)?
Is it because the equals method is meant to test for "absolute" equality rather than "logical" equality (in which case contains(Object o)
would be sufficient)?
推荐答案
设置
是一个集合
将 a.equals(b)== true
视为重复的对象,因此尝试获取已有的同一对象是没有意义的。
A Set
is a Collection
of objects which treats a.equals(b) == true
as duplicates, so it doesn't make sense to try to get the same object you already have.
如果你想从一个集合中尝试 get(Object)
,那么 Map
可能更合适。
If you are trying to get(Object)
from a collection, a Map
is likely to be more appropriate.
你应该写的是
Map<String, String> map = new LinkedHashMap<>();
map.put("1", "Number 1");
map.put("2", null);
String description = set.get("1");
如果对象不在集合中(基于等于),添加它,如果它在集合中(基于等于)给我设置该对象的实例
if an object is not in the set (based on equals), add it, if it is in the set (based on equals) give me the set's instance of that object
在不太可能的情况下你需要这个你可以使用地图
。
In the unlikely event you need this you can use a Map
.
Map<Bar, Bar> map = // LinkedHashMap or ConcurrentHashMap
Bar bar1 = new Bar(1);
map.put(bar1, bar1);
Bar bar1a = map.get(new Bar(1));
这篇关于为什么java.util.HashSet没有get(Object o)方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!