基本的java arraylist

Ale*_*lex 0 java

我不确定为什么我的代码不起作用.我正在尝试使用arraylist创建图形,但此代码似乎不起作用.每当我尝试从arraylist获取节点ID时它返回0.我确信我刚刚做了一些笨拙的事情.ayone可以指出我的错误吗?

private ArrayList<Node> NodeList = new ArrayList<Node>();

public void addNode(int id, String Label, List connections) {   
    NodeList.add(new Station(id, Label, connections));
}

public ArrayList<Node> getNodes() {
    return NodeList;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的主要方法(这些仅用于测试目的)

ArrayList<Integer> connections = new ArrayList<Integer>();
     connections.add(2);
     connections.add(5);
     g.addNode(6, "first",connections );

    System.out.println(""+g.getNodes().get(0).getID());
Run Code Online (Sandbox Code Playgroud)

谢谢你们的兴趣!这是车站类:

    private int id;
    private String stopName;
    private ArrayList connections;

    public Station(int id, String stopName, List connection) {
        id = this.id;
        stopName = this.stopName;
        setConnections(connection);
    }


    public List getConnections() {
        return connections;
    }



    public int getID() {

        return id;
    }


    public String getLabel() {

        return stopName;
    }
Run Code Online (Sandbox Code Playgroud)

kun*_*l18 6

这是两个错误:

id = this.id;
stopName = this.stopName;
Run Code Online (Sandbox Code Playgroud)

它应该是:

this.id = id;
this.stopName = stopName;
Run Code Online (Sandbox Code Playgroud)

看,'this'用于表示调用对象.所以当你像上面那样写时,你会说"这个对象的id = id(参数一)".

当你按照你在问题中所写的那样写作时,

id = this.id;
Run Code Online (Sandbox Code Playgroud)

你正在改变'传递参数id'的值并为其赋值object的id,其默认值为0!这就是为什么你得到的结果为0.