基本java数组列表

基本java数组列表,java,Java,我不知道为什么我的代码不起作用。我正在尝试使用arraylist创建一个图形,但这段代码似乎不起作用。每当我尝试从arraylist获取节点ID时,它都返回0。我肯定我刚做了些笨拙的事。有人能指出我的错误吗 private ArrayList<Node> NodeList = new ArrayList<Node>(); public void addNode(int id, String Label, List connections) { NodeLi

我不知道为什么我的代码不起作用。我正在尝试使用arraylist创建一个图形,但这段代码似乎不起作用。每当我尝试从arraylist获取节点ID时,它都返回0。我肯定我刚做了些笨拙的事。有人能指出我的错误吗

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;
}

在构造函数中,赋值的方式是错误的。你想要

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

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

这是两个错误:

id = this.id;
stopName = this.stopName;
应该是:

this.id = id;
this.stopName = stopName;
请参阅,“this”用于指调用对象。所以当你像上面那样写的时候,你说“这个对象的id=id(参数一)”

当你像你在问题中写的那样写的时候

id = this.id;

您正在更改“已传递参数id”的值,并为其指定对象id的值,其默认值为0!这就是为什么您得到的结果为0。

您能提供一个我们可以运行的示例吗?否则,我们只能猜测您使用的
id
为0,这就是您找到的原因。
Station
a
Node
?不要忘记始终使用lower。请显示
Station(int,String,List)
(可能还有它的超级构造函数)、
Node\getID()
和/或
Station\getID()的实现
@PeterLawrey又添加了一些东西,对不起。+1
id=this.id
是错误的方法,并且以错误的方法复制值。您可以通过将构造函数的签名写入
公共电台(最终int id、最终字符串stopName、最终列表连接)
来强制执行此操作。然后,
id=this.id
将是一个编译时错误,这是您想要的。顺便说一下,不要使用原始
List
s。另外,注意你的unshown
setConnections
方法;你真的想创建一个新的
列表
,而不是共享输入列表。@EricJablow这听起来像是对提问者的评论,而不是对我。我不确定在哪里发表评论。发帖人的问题没有任何理由做出这样的评论。这听起来确实像是针对发帖人,而不是针对我。谢谢,这是解决办法。我是个白痴:(很抱歉浪费了你的时间。别担心!会发生的。。希望你的概念现在清楚了!享受:)@John别忘了标出正确的答案,这样斯大林就得到了他应得的分数;)
this.id = id;
this.stopName = stopName;
id = this.id;