使用HashMap统计二维不同点数结果错误,求排查与修正方案
问题排查与解决方案
问题原因分析
- 逻辑完全偏离需求:你在循环中判断的是同一索引下的x值和y值是否相等,这和“统计不同二维点数量”的目标无关。比如示例中的(2,3),x≠y,会被计入count,最终所有点的x和y都不相等时count为5,完全错误。
- 存储方式错误:没有将二维点作为一个整体处理,拆分存储的x、y坐标无法判断不同索引对应的(x,y)是否为同一个点。
正确实现方案
方案1:自定义Point类(推荐,类型安全)
通过自定义Point类并重写equals和hashCode方法,让HashSet能正确识别重复的点:
import java.util.HashSet; class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; return x == point.x && y == point.y; } @Override public int hashCode() { return 31 * x + y; } } public class Main { public static void main(String[] args) { int[] x = {2, 1, 3, 2, 2}; int[] y = {3, 1, 2, 3, 4}; int n = x.length; HashSet<Point> uniquePoints = new HashSet<>(); for (int i = 0; i < n; i++) { uniquePoints.add(new Point(x[i], y[i])); } System.out.println(uniquePoints.size()); // 输出4 } }
方案2:使用内置SimpleEntry类(无需自定义类)
利用Java内置的AbstractMap.SimpleEntry来封装坐标,它已经实现了equals和hashCode:
import java.util.HashSet; import java.util.AbstractMap; public class Main { public static void main(String[] args) { int[] x = {2, 1, 3, 2, 2}; int[] y = {3, 1, 2, 3, 4}; int n = x.length; HashSet<AbstractMap.SimpleEntry<Integer, Integer>> uniquePoints = new HashSet<>(); for (int i = 0; i < n; i++) { uniquePoints.add(new AbstractMap.SimpleEntry<>(x[i], y[i])); } System.out.println(uniquePoints.size()); // 输出4 } }
方案3:字符串拼接(快速实现,注意歧义)
将x和y用分隔符拼接成字符串存入HashSet,适合快速测试(注意如果坐标包含负数或特殊字符,需用分隔符避免歧义,比如","):
import java.util.HashSet; public class Main { public static void main(String[] args) { int[] x = {2, 1, 3, 2, 2}; int[] y = {3, 1, 2, 3, 4}; int n = x.length; HashSet<String> uniquePoints = new HashSet<>(); for (int i = 0; i < n; i++) { uniquePoints.add(x[i] + "," + y[i]); } System.out.println(uniquePoints.size()); // 输出4 } }
内容的提问来源于stack exchange,提问作者user_program
相关产品推荐
相关产品推荐

