包含函数链表


public class state implements Comparator<state>{
        Point a;
        Point b;
        private int path_cost=0;
        ...
}
    class Point {
        int x;
        int y;
        ...
    }

对于以上,我有:

PriorityQueue<state> openNode= new PriorityQueue<state>();
LinkedList<state> closed =new LinkedList<state>();
state currNode;

我需要检查任何openNodeclosedPoint a是否等于currNodePoint a

如果我必须匹配整个对象,我可以使用contains但在这里我只关心状态类的一个变量(点 a)。我希望该方法检查 PriorityQueue 和 LinkedList 中的所有节点。

加法:我正在考虑在我的priorityQueue和LinkedList上使用Iterator。但我不确定如何使用迭代器读取点 a 的值。

编辑:看起来我有点误解了。这比我想象的要简单。

// I've assumed more conventional names
Point currPoint = currNode.getPointA();
for (State openNode : openNodes) {
    if (openNode.getPointA().equals(currPoint)) {
        return true;
    }
}
for (State closedNode : closedNodes) {
    if (closedNode.getPointA().equals(currPoint)) {
        return true;
    }
}
// No matching points
return false;

您可以使用Guava的Iterables.concat()方法使这稍微简单一些:

for (State node : Iterables.concat(closedNodes, openNodes)) {
    if (node.getPointA().equals(currPoint)) {
        return true;
    }
}
return false;

如果您需要知道哪个节点具有相等的点 A,只需将其更改为:

for (State node : Iterables.concat(closedNodes, openNodes)) {
    if (node.getPointA().equals(currPoint)) {
        return node;
    }
}
return null;

当然,这只会找到一个这样的节点 - 可能有多个匹配项。

您必须在

Point a上为state类提供等于方法,或者只是使用简单的迭代并迭代两个列表进行比较。 contains方法也是如此。

如果您使用任何其他方法,这将非常耗时。

非常奇怪的方法是使用Comparator to check equality

 class PointAComparator implements Comparator<State>
{
    Point p = null;
    public PointAComparator(Point a) {
        p = a;
    }
    @Override
    public int compare(State o1, State o2) {
        return (p.x == o1.a.x && p.y == o1.a.y) ? 1
                : (p.x == o2.a.x && p.y == o2.a.y) ? 1 : -1;
    }
}

上面的比较方法返回 1 表示相等,否则 -1,因此当您进行排序时,每个列表的开头都会有相等的元素。 然后你可以检查第一个元素。

我对对象的函数equals使用了覆盖方法并实现了我的结果。

       class Point {
            int x;
            int y;
            ...
    @Override
    public boolean equals(Object other){
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof Point))return false;
        Point otherPoint = (Point)other;
        return (this.x==otherPoint.getX() && this.y==otherPoint.getY() )? true : false;
    }
        }

public class state implements Comparator<state>{
            Point a;
            Point b;
            private int path_cost=0;
            ...
    @Override
    public boolean equals(Object other){
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof state))return false;
        state otherState = (state)other;
        return ((this.a).equals(otherState.a))? true : false;
    }
    }

最新更新