2012-09-23 46 views
3
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。但我不知道如何使用Iterator读取Point a的值。

+0

您需要编写一个。你有问题吗? –

+0

我不能想到一个方法来做到上述! – change

回答

2

编辑:看起来像我误解了一些。这比我想象的更简单。

// 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; 

你可能使用番石榴的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; 

那只会找到一个这样的节点当然是 - 重新可能是多个比赛。

+0

如果currNode的Point a有一些匹配,我需要使用'path_cost'变量。在这种情况下,我将失去这种联系。我正在考虑在我的priorityQueue和LinkedList上使用Iterator。但我不知道如何使用Iterator读取Point a的值。 – change

+0

@parin:那么这就改变了这个问题......你最初只想知道*是否有这样一个节点*。我编辑了我的答案。 –

0

您将不得不在Point a上为state类提供equals方法,或者只是使用简单的迭代并迭代两个List以进行比较。 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,所以当你做排序,则每个列表将在开始这是相等的元素。然后你可以检查第一个元素。

0

我使用方法覆盖功能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; 
    } 
    }