【发布时间】:2021-08-31 17:01:40
【问题描述】:
例如:
class SomeClass
{
int x;
int y;
public SomeClass(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SomeClass that = (SomeClass) o;
return x == that.x;
}
public int hashCode()
{
return Objects.hash(x);
}
}
然后:
HashSet<SomeClass> hs = new HashSet<>();
SomeClass a = new SomeClass(3, 5);
SomeClass b = new SomeClass(3, 6);
hs.add(a);
hs.add(b);
我知道 HashSet 不会添加 b。但我希望它以某种方式返回对象a,因为a 和b 并不完全相同。
HashSet 会将它们视为相等并且不会添加b,在插入失败后我想检查对象a。
tldr:
我需要一个可以做类似hs.getDuplicateOf(b) 的方法,这可能吗?
【问题讨论】:
-
不清楚。
add()返回boolean。 -
if (hs.contains(b)) { SomeClass copy = hs.stream().filter(o -> o.equals(b)).findFirst().get(); }
标签: java collections hashset