2013-05-06 76 views
1

我想使用strategy pattern模塊化我的A *實現中的啓發式,但在分離它時遇到了一些麻煩。我試圖與使用我的啓發下面的方式Comparator初始化我的優先級隊列:如何在A *(運行時啓發式)中模塊化啓發式

public AStarSearch(Graph g, AStarHeuristic heuristic) { 
     this.heuristic = heuristic; 
     this.open = new PriorityQueue<Node>(10, new Comparator<Node>(){ 
      @Override 
      public int compare(Node n1, Node n2) { 
       int fScoreOne = n1.getTotalPathWeight() + heuristic.calculate(n1, open); 
       int fScoreTwo = n1.getTotalPathWeight() + heuristic.calculate(n1, open); 
       if (fScoreOne < fScoreTwo) 
        return 1; 
       else if (fScoreOne > fScoreTwo) 
        return -1; 
       return 0; 
      } 
     }); 
    } 

,但我得到:「不能引用內部非最終變量啓發並以不同的方法定義的內部類」

我在加權完整圖上運行它,計劃使用向開放集合中最近節點移動的基本啓發式方法(我沒有目標節點,只需要一組節點訪問)。當然,爲了找到開放集合中節點的最小權重邊緣,我需要開放節點的列表/隊列和當前節點(它有一個邊緣列表),所以我製作了啓發式接口,如下所示:

public interface AStarHeuristic { 
    public int calculate(Node curr, Queue<Node> open); 
} 

如何分離出我的heurisitc,以便它可以用來在運行時排序我的隊列?

回答

2

這裏的問題是你正在創建一個匿名的內部類,並試圖在調用函數中引用一個局部變量(這裏是heuristic)。爲了做到這一點,Java要求變量標記爲final。如果您嘗試將方法更改爲

public AStarSearch(Graph g, final AStarHeuristic heuristic) { 
    // ... Same as before ... 
} 

該問題應該消失。

希望這會有所幫助!