Stream and the distinct operation(流和不同的操作)
问题描述
我有以下代码:
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
方法的一般约定,该约定声明等于对象必须具有相同的哈希码.
Note that it is generally necessary to override the
hashCode
method whenever this method is overridden, so as to maintain the general contract for thehashCode
method, which states that equal objects must have equal hash codes.
显然,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.
这篇关于流和不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:流和不同的操作


基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01