问题描述
我有以下代码:
class C
{
String n;
C(String n)
{
this.n = n;
}
public String getN() { return n; }
@Override
public boolean equals(Object obj)
{
return this.getN().equals(((C)obj).getN());
}
}
List<C> cc = Arrays.asList(new C("ONE"), new C("TWO"), new C("ONE"));
System.out.println(cc.parallelStream().distinct().count());
但我不明白为什么 distinct
返回 3 而不是 2.
but I don't understand why distinct
returns 3 and not 2.
推荐答案
您还需要覆盖 C
类中的 hashCode
方法.例如:
You need to also override the hashCode
method in class C
. For example:
@Override
public int hashCode() {
return n.hashCode();
}
当两个 C
对象相等时,它们的 hashCode
方法必须返回相同的值.
When two C
objects are equal, their hashCode
methods must return the same value.
接口Stream
的API文档没有提到这一点,但是众所周知,如果你重写equals
,你也应该重写hashCode
.Object.equals()
的 API 文档提到了这一点:
The API documentation for interface Stream
does not mention this, but it's well-known that if you override equals
, you should also override hashCode
. The API documentation for Object.equals()
mentions this:
请注意,每当重写 hashCode
方法时,通常都需要重写该方法,以维护 hashCode
方法的一般约定,该约定声明等于对象必须具有相同的哈希码.
显然,Stream.distinct()
确实使用了对象的哈希码,因为当你像我上面展示的那样实现它时,你会得到预期的结果:2.
Apparently, Stream.distinct()
indeed uses the hash code of the objects, because when you implement it like I showed above, you get the expected result: 2.
这篇关于流和不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!