Getting an element from a Set(从 Set 中获取元素)
问题描述
Set 为什么不提供一个操作来获取一个等于另一个元素的元素?
Why doesn't Set provide an operation to get an element that equals another element?
Set<Foo> set = ...;
...
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo); // get the Foo element from the Set that equals foo
我可以问 Set 是否包含一个等于 bar 的元素,那为什么我不能得到那个元素呢?:(
I can ask whether the Set contains an element equal to bar, so why can't I get that element? :(
为了澄清,equals 方法被覆盖,但它只检查其中一个字段,而不是全部.所以两个被认为相等的 Foo 对象实际上可以有不同的值,这就是为什么我不能只使用 foo.
To clarify, the equals method is overridden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo.
推荐答案
如果元素相等,那么获取元素就没有意义了.Map 更适合这个用例.
There would be no point of getting the element if it is equal. A Map is better suited for this usecase.
如果你仍然想找到元素,你别无选择,只能使用迭代器:
If you still want to find the element you have no other option but to use the iterator:
public static void main(String[] args) {
Set<Foo> set = new HashSet<Foo>();
set.add(new Foo("Hello"));
for (Iterator<Foo> it = set.iterator(); it.hasNext(); ) {
Foo f = it.next();
if (f.equals(new Foo("Hello")))
System.out.println("foo found");
}
}
static class Foo {
String string;
Foo(String string) {
this.string = string;
}
@Override
public int hashCode() {
return string.hashCode();
}
@Override
public boolean equals(Object obj) {
return string.equals(((Foo) obj).string);
}
}
这篇关于从 Set 中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Set 中获取元素
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
