Java:为什么我的对象数组会覆盖循环中的所有先前数据?

时间:2014-11-22 15:40:45

标签: java arrays loops overwrite

我尝试在阵列中的特定位置创建一个节点数组。

例如:
我在数组中添加一个节点并将其编号设置为1 我在下一个位置的数组中添加另一个节点,并将其数字设置为2 两个节点现在都得到了数字2.

代码示例:

public static String run(InputStream in) {

    Scanner sc = new Scanner(in);

    //indicating values
    sc.nextInt(); /* int vertices = */
    int edge = sc.nextInt();
    int start = sc.nextInt();
    int end = sc.nextInt();

    if (start == end) {
        sc.close();
        Path = "yes";
    } else {
        nodes = new Node[edge + 1];
        for (int i = 1; i < edge; i++) {

            //Node values
            int number = sc.nextInt();
            int next = sc.nextInt();
            sc.nextInt(); /* int distance = */

            Node node = new Node(number, next);

            if (nodes[number] == null) {
                nodes[number] = (node);
            } else {
                nodes[number].addChild(next);
            }
        }
        hasPath(nodes[start], end);

    }
    sc.close();

    return Path;
}

节点代码示例:

import java.util.ArrayList;

public class Node {

private ArrayList<Integer> childs = new ArrayList<Integer>();

private static int number;

public Node(int n, int next){
    number = n;
    childs.add(next);
}

public int getNumber(){
    return number;
}

public void addChild(int child){
    childs.add(child);
}  

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

问题在于声明number成员 static 。这意味着Node 只有一个此类成员,而不是每个实例都有自己的成员。只需将其定义为实例变量,您应该没问题:

public class Node {
    private ArrayList<Integer> childs = new ArrayList<Integer>();
    private int number; // Note the static was removed
    // rest of the class