【问题标题】:Java: Why is my array of objects overwriting all the previous data inside a loop?Java:为什么我的对象数组会覆盖循环内的所有先前数据?
【发布时间】:2015-01-20 15:36:45
【问题描述】:

我尝试创建一个节点数组,其中一个节点位于数组中的特定位置。

例如:
我在数组中添加一个节点并将其编号设置为 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);
}  

谁能帮帮我?

【问题讨论】:

    标签: java arrays loops overwrite


    【解决方案1】:

    问题在于声明number 成员static。这意味着Node class 只有一个这样的成员,而不是每个 instance 都有自己的成员。只需将其定义为实例变量,就可以了:

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

    【讨论】:

    • 完成了这项工作,谢谢!
    • @EmielRietdijk:如果这解决了您的问题,您应该将其标记为“已接受”!
    猜你喜欢
    • 2012-06-21
    • 2021-11-20
    • 1970-01-01
    • 2017-08-12
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2017-09-15
    相关资源
    最近更新 更多