作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 Java 数组。数组的每个条目都是一对数字(x 和 y 坐标)。
从技术上讲,我的数组示例是:
setOfPoints = {(1,2), (3,4), (5,6), (1,9), (7,4)}
我如何搜索该列表并检查 (3,4) 是否是该集合的一部分?
理想情况下,我想做一个 Java 函数 isCoordinateInSet((3,4), setOfPoints)。我还想避免使用可能会增加操作时间的 for 循环。我正在考虑使用 Java Maps fpr 这个任务。你怎么看?
我没有遵循上面的 Java 语法,但我是这样描述的,以便更好地解释我想要做什么。
非常感谢您的意见。
谢谢。
最佳答案
public class Point{
private int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
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;
if (x != point.x) return false;
if (y != point.y) return false;
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
Set<Point> points = new HashSet<>();
points.add(new Point(3,4));
points.add(new Point(5,6));
points.add(new Point(1,2));
points.add(new Point(3,5));
System.out.println(points.contains(new Point(3,4)));
System.out.println(points.contains(new Point(1,2)));
System.out.println(points.contains(new Point(2,4)));
关于java - 如何在 Java 中搜索坐标数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434681/
我是一名优秀的程序员,十分优秀!