
在Java开发中,我们经常需要处理包含自定义对象的集合,并从中筛选出唯一的元素。直观上,许多开发者会想到使用HashSet或Stream API中的distinct()方法。然而,当对象的唯一性判断需要基于其内部属性而非简单的对象引用时,仅凭默认的实现往往无法达到预期效果。本文将以一个PointType类为例,深入剖析这一问题,并提供一套健壮的解决方案。
假设我们有一个表示二维坐标点的PointType类,其包含x和y两个double类型属性。我们希望当两个PointType对象的x和y值都相同时,它们被认为是相等的,从而在集合中只保留一个实例。
以下是初始的PointType类及其equals方法实现:
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) {
if (other instanceof PointType && this.x == ((PointType) other).x && this.y == ((PointType) other).y) {
return true;
}
return false;
}
// 缺少hashCode方法
}在测试代码中,我们创建了几个PointType实例,其中p1和p2表示相同的坐标(1.0, 2.0),p3和p4表示相同的坐标(2.0, 2.0)。我们尝试使用HashSet和Stream.distinct()来获取唯一元素:
立即学习“Java免费学习笔记(深入)”;
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 UniquenessTest {
@Test
public void testUniqueness() {
Set<PointType> setA = new HashSet<>();
Set<PointType> setB = new HashSet<>();
ArrayList<PointType> listA = new ArrayList<>();
ArrayList<PointType> 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.toCollection(ArrayList::new));
listB.add(p1);
listB.add(p2);
listB.add(p3);
listB.add(p4);
listB = listB.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
assertTrue(p1.equals(p2)); // 通过 (因为equals被重写)
assertTrue(p3.equals(p4)); // 通过 (因为equals被重写)
assertTrue(setA.size() == 1); // 失败!预期1,实际2 (p1和p2虽然equals,但hashCode不同)
assertTrue(setB.size() == 2); // 失败!预期2,实际4
assertTrue(listA.size() == 1); // 失败!预期1,实际2
assertTrue(listB.size() == 2); // 失败!预期2,实际4
}
}上述测试结果表明,尽管我们重写了equals方法,但HashSet和Stream.distinct()并未如预期般工作。这揭示了Java中自定义对象唯一性判断的关键——equals()和hashCode()方法必须协同工作,并遵循其严格的契约。
要使自定义对象在集合中实现基于属性的唯一性,我们需要正确地重写equals()和hashCode()方法。
原始的equals方法存在几个问题:
以下是更健壮的equals方法实现:
@Override
public boolean equals(Object o) {
// 1. 引用同一对象,直接返回true
if (this == o) return true;
// 2. 检查o是否为null或类型不匹配
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;
}这是解决问题的关键。Java的Object类规定,如果两个对象通过equals()方法比较为相等,那么它们的hashCode()方法必须产生相同的整数结果。反之则不要求。HashSet和HashMap等基于哈希的集合类在存储和查找元素时,会首先使用hashCode()来确定对象的存储桶位置,然后再使用equals()进行精确比较。如果hashCode()不一致,即使equals()返回true,集合也可能认为它们是不同的对象。
一个好的hashCode实现应满足以下条件:
我们可以使用Objects.hash()辅助方法来方便地生成hashCode,它会根据传入的属性值生成一个哈希码。
import java.util.Objects; // 导入Objects类
@Override
public int hashCode() {
return Objects.hash(x, y); // 根据x和y属性生成哈希码
}结合上述修改,PointType类的完整实现如下:
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;
}
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() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "PointType{" +
"x=" + x +
", y=" + y +
'}';
}
}现在,当我们使用更新后的PointType类运行之前的测试代码时,所有断言都将通过:
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 UniquenessTest {
@Test
public void testUniqueness() {
Set<PointType> setA = new HashSet<>();
Set<PointType> setB = new HashSet<>();
ArrayList<PointType> listA = new ArrayList<>();
ArrayList<PointType> 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);
setA.add(p1);
setA.add(p2); // p2与p1 equals且hashCode相同,不会被添加
setA.add(p1);
setA.add(p2);
assertTrue(setA.size() == 1); // 通过!
setB.add(p1);
setB.add(p2); // p2与p1重复
setB.add(p3);
setB.add(p4); // p4与p3重复
assertTrue(setB.size() == 2); // 通过! (包含(1.0,2.0)和(2.0,2.0)各一个)
listA.add(p1);
listA.add(p2);
listA.add(p1);
listA.add(p2);
listA = listA.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
assertTrue(listA.size() == 1); // 通过! (Stream.distinct()依赖于equals和hashCode)
listB.add(p1);
listB.add(p2);
listB.add(p3);
listB.add(p4);
listB = listB.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
assertTrue(listB.size() == 2); // 通过!
}
}现在,HashSet和Stream.distinct()都能正确识别出具有相同x和y属性的PointType对象为同一个逻辑实体,并只保留一个。
通过正确理解和实现equals()和hashCode(),我们可以确保Java集合框架能够准确无误地处理自定义对象的唯一性,从而构建更健壮、可预测的应用程序。
以上就是Java自定义对象唯一性:深入理解equals与hashCode的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号