2012-10-05 165 views
5

有沒有辦法在Java中將List列爲二維?Java中的二維列表

這種情況: 我有一個節點,邊緣和每邊重量的圖。現在我需要一個數據結構來存儲每個節點: 一)及其鄰國 B)每個neigbour

首先,我想創建一個新的類「節點」與identifyer又像兩事的邊緣的重量二維數組來存儲鄰居識別器和邊緣權重。但是沒有給出每個節點的鄰居數量,並且可能在運行時動態增加。因此我認爲二維數組並不適合這裏。

我認爲這將有可能在類「節點」就像一個列表:

List<node> neighbours = new ArrayList<node>(); 

但顯然這只是處理相鄰節點 - 不是他們的邊的權重。

有沒有人有提示如何構建這樣一個「圖」,其中每個節點的鄰居的身份和相應的邊權重存儲?

感謝您閱讀:-)

+0

2維數組會做,但如果實現它,2D數組的方式是不必要的,你是靈活的。我可以建議在java中使用MAPS嗎? http://docs.oracle.com/javase/6/docs/api/java/util/Map.html –

+2

類似:http://stackoverflow.com/questions/745048/looking-for-a-simple- java-api-for-creating-graphs-edges-nodes – yiannis

+0

[JGraphT](http://jgrapht.sourceforge.net/)非常棒,是Java地圖的絕佳替代品! – coroner

回答

4

最直接的方法是使用HashMap

class Edge { 
// represents edge with destination node and it's weight 
     private final Node node; 
     private final int weight; 

     Edge(Node node, int weight) { 
      this.node = node; 
      this.weight = weight; 
     } 

    } 

// represents map which holds all outgoing edges keyed by source nodes. 
    Map<Node, Set<Edges>> edgesByOutgoingNodes = new HashMap<Node, Set<Edges>>(); 
+0

@coroner HashMap是要去的路.. ;-) –

+0

非常感謝! :-) – coroner

0

你可以做這樣的事情:

List<Connection> connections = new ArrayList<Connection>(); 

其中的 '連接' 是定義爲:

Class Connection { 
    private int weight; 
    private Node node; 

    .... add getters/setters here .... 
} 
0

Guava中的Table接口可能有些用處。我從來沒有用過它,但我聽說它很好。這個create方法可能有些用處