求助修正Java中Quadrilateral类的isTheSame方法实现
修正Quadrilateral类的isTheSame方法
核心修正思路
要满足需求,isTheSame需要完成三个核心校验:类型匹配、顶点数量一致、顶点完全重合(顺序无关,兼容double精度误差)。针对你提到的错误,做以下修正:
修正后的代码实现
public class Quadrilateral extends Figure { private static final double DELTA = 1e-6; // 精度阈值,可根据需求调整 private List<Point> vertices; // 存储四边形的四个顶点 @Override public boolean isTheSame(Figure other) { // 1. 先校验类型,非Quadrilateral直接返回false if (!(other instanceof Quadrilateral)) { return false; } Quadrilateral otherQuad = (Quadrilateral) other; // 2. 顶点数量不一致,直接不匹配 if (this.vertices.size() != otherQuad.vertices.size()) { return false; } // 3. 复制对方顶点列表,用于逐个匹配并移除,避免重复匹配 List<Point> remainingOtherVertices = new ArrayList<>(otherQuad.vertices); // 4. 遍历当前顶点,在对方顶点中寻找精度范围内匹配的点 for (Point currentPoint : this.vertices) { boolean matchFound = false; Iterator<Point> iterator = remainingOtherVertices.iterator(); while (iterator.hasNext()) { Point otherPoint = iterator.next(); // 用DELTA处理double精度误差 if (Math.abs(currentPoint.x - otherPoint.x) < DELTA && Math.abs(currentPoint.y - otherPoint.y) < DELTA) { matchFound = true; iterator.remove(); // 找到匹配点后移除,防止重复匹配 break; } } // 有一个顶点找不到匹配,直接返回false if (!matchFound) { return false; } } // 所有顶点都匹配,且对方顶点已全部被匹配移除 return remainingOtherVertices.isEmpty(); } // 内部顶点类示例(如果项目中未定义) static class Point { double x; double y; public Point(double x, double y) { this.x = x; this.y = y; } } }
关键错误修正点
- 修复类型判断逻辑:替换了原代码中直接返回true的错误类型校验,改为
instanceof严格判断类型,不匹配直接返回false - 移除无效对象创建:删除了原代码中重新创建当前对象的冗余逻辑,直接对传入的
other对象进行强转和校验 - 实现顺序无关的顶点匹配:通过复制顶点列表+遍历移除的方式,确保顶点顺序不影响判断,只要所有顶点在精度范围内重合即匹配
- 兼容double精度误差:使用
DELTA阈值比较顶点的x、y坐标,避免因浮点数精度问题导致的误判
内容的提问来源于stack exchange,提问作者Andrii
相关产品推荐
相关产品推荐

