2012-09-23 45 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; 
    } 
    }