2014-09-23 73 views
0

我有一个非常简单的图形执行如下命令:爪哇 - 改变图形节点的标签不更新连接标签

class Graph{  
    ArrayList<Node> nodes; 
    ... 

    public void addNode(Node n){ 
     nodes.add(n); 
    } 

    void changeLabel(int index, char label){ 
     nodes.get(index).label = label; 
    }   
} 

class Node{ 
    char label; 
    ArrayList<Node> connections; 

    public void addConnection(Node other){ 
     connections.add(other); 
    }  
} 

接下来,我创建了一个循环图如下:

Graph g = new Graph(); 
Node a = new Node('A'); 
Node b = new Node('B'); 
Node c = new Node('C'); 

//code to add nodes to graph 
g.addNode(a); 
g.addNode(b); 
g.addNode(c); 

//code to add each node as connection to every other node 
a.addConnection(b); 
a.addConnection(c); 
b.addConnection(a); 
b.addConnection(c); 
.... 

然后,我改变标签上的图中的节点中的一个(比如A至E):

g.changeLabel(0, 'E'); 

现在,当我显示该图形节点s,我可以看到更新的标签。但是,当我遍历节点的连接时,我仍然将标签取为'A'。为什么这样?

回答

0

我确定问题不在您发布的代码片段中。下面的程序正常工作。尝试将它与你的匹配。

import java.util.List; 
import java.util.ArrayList; 
public class Temp_1 { 
    public static void main(String[] args) { 
    Graph graph = new Graph(); 
     graph.nodes = new ArrayList<Node>(); 
     //add nodes 
     Node node1 = new Node(); 
     node1.label = 'A'; 

     Node node2 = new Node(); 
     node2.label = 'B'; 

     graph.nodes.add(node1); 
     graph.nodes.add(node2); 

     printNodes(graph); 
     graph.nodes.get(0).addConnection(graph.nodes.get(1)); 
     graph.nodes.get(1).addConnection(graph.nodes.get(0)); 

     printConnections(graph); 


     graph.changeLabel(0, '1'); 

     System.out.println("after changing label"); 
     printNodes(graph); 
     printConnections(graph); 

    } 

    static void printNodes(Graph g) { 
    System.out.println("Printing Nodes "); 
    for (Node elem_ : g.nodes) System.out.println(elem_.label); 
    } 

    static void printConnections(Graph g) { 

    System.out.println("Printing Connections "); 
    for (Node elem_ : g.nodes) { 
     System.out.println("Printing Connections for node [" + elem_.label + "]"); 
     for (Node connection_ : elem_.connections) { 
     System.out.println(connection_.label); 
     } 
    } 

    } 
} 


class Graph{ 

public ArrayList<Node> nodes; 


void changeLabel(int index, char label){ 
    nodes.get(index).label = label; 
    } 

} 

class Node{ 

char label; 
ArrayList<Node> connections = new ArrayList<Node>(); 

public void addConnection(Node other){ 
    connections.add(other); 
} 

} 
+0

对不起,我忘了指定添加新连接的方式。我编辑了添加连接的代码。不知道这是否有所作为。 – drunkenfist 2014-09-23 23:47:51

+0

你还可以发布Graph类的addNode方法吗? – SJha 2014-09-23 23:49:41

+0

嗯,我似乎犯了一个错误。抱歉。谢谢。 – drunkenfist 2014-09-24 00:11:22