Java - 更改图形节点的标签不会更新连接中的标签

时间:2014-09-23 22:01:54

标签: java data-structures

我有一个非常简单的Graph实现,如下所示:

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');

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

1 个答案:

答案 0 :(得分: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);
}

}