【问题标题】:How to search an array of coordinates in Java?如何在Java中搜索坐标数组?
【发布时间】:2012-11-17 20:53:47
【问题描述】:

我有一个 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 语法,但我是这样描述的,以便更好地解释我想要做什么。

非常感谢您的意见。

谢谢。

【问题讨论】:

  • 当你说“每个条目都是一对数字”时——你的意思是你已经创建了自己的类吗?使用地图很好,但这会消除排序 - 那时它是地图,而不是数组。事实上,一套就足够了吗?在解释您所拥有的方面,使用 Java 代码会更加更清晰。您还应该明确您的要求。
  • @JonSkeet 如何使用 multihashmap 找到解决方案?
  • @BlueBullet:我认为为一对坐标设置一个单独的类会相当干净。这在 OP 的问题域中听起来像是一个有意义的概念。

标签: java arrays search coordinates


【解决方案1】:
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)));

【讨论】:

  • 这段漂亮的代码具有惊人的魅力!谢谢 assylias 和 user1121883!
【解决方案2】:

您可以创建一个类 Coordinate 来保存 (x,y) 对并覆盖其 equals/hashcode 方法以使具有相同 x 和 y 的两个实例相等。

然后在数组中为每一对创建一个坐标实例,并将它们添加到Set&lt;Coordinate&gt;,例如HashSet

那么你isCoordinateInSet 只是对set.contains(new Coordinate(3,4)); 的调用。

【讨论】:

    【解决方案3】:

    Apache 公共库有一个名为MultiHashMap 的类,它位于org.apache.commons.collections 包中。我认为您可以使用MultiHashMap 来搜索特定坐标。

    MultiMap mhm = new MultiHashMap();
    mhm.put(3,5);
    mhm.put(3,4);
    mhm.put(5,6);
    mhm.put(3,8);
    List list = (List) mhm.get(3);
    

    list 将包含 5,4 和 8。找到 x-coordinate 值后,您将在此列表中搜索 y-coordinate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2019-08-04
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多