I'm not sure why my code isn't working. I'm trying to create a graph using an arraylist but this code doesn't appear to work. Whenever I try and get a node ID from the arraylist it returns 0. I'm sure I've just done something clumsy. Can ayone point out my mistake?
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;
}
Then in my main method (these are just for testing purposes)
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());
Thanks for the interest guys! Here is the station class:
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;
}
2 Answers 2
These are two mistakes:
id = this.id;
stopName = this.stopName;
It should be:
this.id = id;
this.stopName = stopName;
See, 'this' is used to refer to calling object. So when you write like above, you say that "This object's id = id (argument one)".
And when you write as you have written in your question,
id = this.id;
you are changing the value of 'passed argument id' and assigning it the value of object's id, whose default value is 0! That's why you were getting the result as 0.
In your constructor, the assignments are the wrong way around. You want
public Station(int id, String stopName, List connection) {
this.id = id;
this.stopName = stopName;
setConnections(connection);
}
instead of
public Station(int id, String stopName, List connection) {
id = this.id;
stopName = this.stopName;
setConnections(connection);
}
5 Comments
id = this.id; is the wrong way around and copies the value the wrong way as well.public Station(final int id, final String stopName, final List connection). Then, id = this.id will be a compile-time error, which you want. By the way, don't use raw Lists. And, watch out in your unshown setConnections method; you really want to create a new List, not share the input list.
idof 0 which is why that is what you find.StationaNode?Station(int, String, List)(and possibly its super constructor),Node#getID()and/orStation#getID().