在java开发中,我们经常需要处理包含自定义对象的集合,并从中筛选出唯一的元素。直观上,我们可能会尝试使用hashset或stream api中的distinct()方法。然而,当这些方法未能按照预期工作时,问题往往指向自定义对象中equals()和hashcode()方法的实现。本文将通过一个具体的pointtype类示例,详细解析这一常见问题及其解决方案。
Java集合框架中的许多类(如HashSet、HashMap)以及Stream API的distinct()操作,都依赖于对象的equals()和hashCode()方法来判断对象的逻辑相等性。
当我们需要根据对象的属性(而不是它们的内存地址)来判断唯一性时,就必须正确地重写这两个方法。
假设我们有一个PointType类,表示一个二维点,包含x和y两个双精度浮点数属性:
public class PointType {
private double x;
private double y;
public PointType(double x, double y) {
this.x = x;
this.y = y;
}
// 初始尝试的equals方法
@Override
public boolean equals(Object other) {
// 这里的比较存在缺陷,且缺少hashCode()的配合
if (other instanceof PointType && this.x == ((PointType) other).x && this.y == ((PointType) other).y) {
return true;
}
return false;
}
// 缺少hashCode()方法
// ...
}在上述代码中,我们尝试重写equals方法来比较x和y属性。然而,当使用HashSet或Stream.distinct()进行去重时,可能会发现结果不符合预期。例如:
import org.junit.jupiter.api.Test; // 假设使用JUnit 5 import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertTrue; public class PointTypeUniquenessTest { @Test public void testUniqueness() { Set
setA = new HashSet<>(); Set setB = new HashSet<>(); List listA = new ArrayList<>(); List listB = new ArrayList<>(); PointType p1 = new PointType(1.0, 2.0); PointType p2 = new PointType(1.0, 2.0); // 逻辑上与p1相等 PointType p3 = new PointType(2.0, 2.0); PointType p4 = new PointType(2.0, 2.0); // 逻辑上与p3相等 // 尝试使用HashSet setA.add(p1); setA.add(p2); setA.add(p1); setA.add(p2); setB.add(p1); setB.add(p2); setB.add(p3); setB.add(p4); // 尝试使用ArrayList和Stream listA.add(p1); listA.add(p2); listA.add(p1); listA.add(p2); listA = listA.stream().distinct().collect(Collectors.toList()); listB.add(p1); listB.add(p2); listB.add(p3); listB.add(p4); listB = listB.stream().distinct().collect(Collectors.toList()); assertTrue(p1.equals(p2)); // 通过 (因为equals被重写了) assertTrue(p3.equals(p4)); // 通过 assertTrue(setA.size() == 1); // 失败!预期为1,实际为2 (因为p1和p2哈希码不同) assertTrue(setB.size() == 2); // 失败!预期为2,实际为4 (因为p1,p2,p3,p4哈希码都不同) assertTrue(listA.size() == 1); // 失败!预期为1,实际为2 assertTrue(listB.size() == 2); // 失败!预期为2,实际为4 } }
上述测试结果表明,尽管p1.equals(p2)通过了,但HashSet和Stream.distinct()未能正确识别逻辑上相等的对象。这是因为HashSet和distinct()不仅依赖于equals(),还高度依赖于hashCode()方法。
要解决上述问题,我们需要对PointType类进行两项关键改进:
原始的equals方法存在两个小问题:
一个更健壮的equals()实现应遵循以下约定:
修正后的equals()方法:
import java.util.Objects; // 导入Objects工具类
public class PointType {
private double x;
private double y;
public PointType(double x, double y) {
this.x = x;
this.y = y;
}
// Getter方法 (可选,但通常推荐)
public double getX() { return x; }
public double getY() { return y; }
@Override
public boolean equals(Object o) {
// 1. 内存地址相同,直接返回true
if (this == o) return true;
// 2. o为null或类型不一致,直接返回false
if (o == null || getClass() != o.getClass()) return false;
// 3. 类型转换
PointType pointType = (PointType) o;
// 4. 比较关键属性,使用Double.compare处理浮点数比较
return Double.compare(pointType.x, x) == 0 &&
Double.compare(pointType.y, y) == 0;
}
// ... 稍后添加hashCode()
}getClass() != o.getClass() 确保了只有当两个对象的运行时类型完全相同时才可能相等。这比 instanceof 更严格,更适用于某些场景。Double.compare(double d1, double d2) 是比较两个double值的推荐方式,它能正确处理NaN、正负零等特殊情况。
当且仅当equals()方法被重写时,hashCode()方法也必须被重写。 这是Java中一个非常重要的契约。如果两个对象根据equals()方法是相等的,那么它们的hashCode()方法必须产生相同的整数结果。反之则不要求,即不同的对象可以有相同的哈希码(哈希冲突),但哈希码相同不代表对象一定相等。
一个糟糕的hashCode()实现(例如,总是返回一个常数)会导致哈希表性能急剧下降,因为它将所有对象都放入同一个“桶”中,退化为链表操作。一个好的hashCode()实现应该:
Java 7 引入的 java.util.Objects 工具类提供了 Objects.hash() 方法,可以方便地生成基于多个字段的哈希码,强烈推荐使用。
修正后的hashCode()方法:
import java.util.Objects;
public class PointType {
private double x;
private double y;
public PointType(double x, double y) {
this.x = x;
this.y = y;
}
// Getter方法
public double getX() { return x; }
public double getY() { return y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PointType pointType = (PointType) o;
return Double.compare(pointType.x, x) == 0 &&
Double.compare(pointType.y, y) == 0;
}
@Override
public int hashCode() {
// 使用Objects.hash()方法生成哈希码,基于所有参与equals比较的字段
return Objects.hash(x, y);
}
}现在,有了正确实现的equals()和hashCode()方法,我们再次运行之前的测试:
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PointTypeUniquenessTest {
@Test
public void testUniqueness() {
Set setA = new HashSet<>();
Set setB = new HashSet<>();
List listA = new ArrayList<>();
List listB = new ArrayList<>();
PointType p1 = new PointType(1.0, 2.0);
PointType p2 = new PointType(1.0, 2.0);
PointType p3 = new PointType(2.0, 2.0);
PointType p4 = new PointType(2.0, 2.0);
// 使用HashSet
setA.add(p1);
setA.add(p2);
setA.add(p1);
setA.add(p2);
setB.add(p1);
setB.add(p2);
setB.add(p3);
setB.add(p4);
// 使用ArrayList和Stream
listA.add(p1);
listA.add(p2);
listA.add(p1);
listA.add(p2);
listA = listA.stream().distinct().collect(Collectors.toList());
listB.add(p1);
listB.add(p2);
listB.add(p3);
listB.add(p4);
listB = listB.stream().distinct().collect(Collectors.toList());
assertTrue(p1.equals(p2)); // 通过
assertTrue(p3.equals(p4)); // 通过
assertTrue(setA.size() == 1); // 通过!现在setA只有一个元素
assertTrue(setB.size() == 2); // 通过!现在setB只有两个元素
assertTrue(listA.size() == 1); // 通过!
assertTrue(listB.size() == 2); // 通过!
}
} 所有测试现在都将通过。这证明了正确重写equals()和hashCode()方法对于自定义对象在哈希集合和Stream.distinct()操作中实现逻辑唯一性至关重要。
在Java中处理自定义对象的唯一性问题时,仅仅重写equals()方法是不够的。为了确保HashSet、HashMap以及Stream.distinct()等机制能正确识别逻辑上相等的对象,我们必须同时并正确地重写equals()和hashCode()方法。遵循Java的equals和hashCode契约,并利用现代Java API(如Objects.hash()和Double.compare()),可以构建健壮且高效的自定义对象相等性判断逻辑。