我已经看到其他关于根据索引值从 Set
获取对象的问题,我理解为什么这是不可能的。但是我无法找到一个很好的解释来解释为什么不允许通过对象获取,所以我想我会问。
HashSet
由 HashMap
支持,因此从中获取对象应该非常简单。就像现在一样,看来我必须遍历 HashSet
中的每个项目并测试似乎没有必要的相等性。
我可以只使用 Map
但我不需要 key:value 对,我只需要一个 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 方法旨在测试“绝对”相等而不是“逻辑”相等(在这种情况下 contains(Object o)
就足够了)?
最佳答案
Java map /集合备忘单
它会包含键/值对还是仅包含值?
1) If it contains pairs, the choice is a map. Is order important?
. 1-1) If yes, follow insertion order or sort by keys?
。 . 1-1-1) 如果已订购,LinkedHashMap
。 . 1-1-2) 如果已排序,TreeMap
。 1-2) 如果顺序不很重要,HashMap
2) If it stores only values, the choice is a collection. Will it contain duplicates?
。 2-1) 如果是,ArrayList
. 2-2) If it will not contain duplicates, is primary task searching for elements (contains/remove)?
。 . 2-2-1) 如果 no,ArrayList
. . 2-2-2) If yes, is order important?
。 . . 2-2-2-1) 如果顺序不重要,HashSet
. . . 2-2-2-2) If yes, follow insertion order or sort by values?
。 . . . 2-2-2-2-1) 如果有序,LinkedHashSet
。 . . . 2-2-2-2-2) 如果排序,TreeSet
关于java - 为什么 java.util.HashSet 没有 get(Object o) 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13863506/