Hi I have 2 classes in Java, Gossip and Node, I want that Gossip will hold a list of all the objects of Node class and I want that each Node object will also have that list. I tried to write it in the following way:
public class Node {
private Boolean val = null;
private LinkedList<Node> list;
static Random rand = new Random();
public Node(LinkedList<Node> list) {
this.list=list;
}
... the rest of Node functions ...
}
and in the Gossip contractor:
public class Gossip {
private int count;
private int n;
private LinkedList<Node> list;
public Gossip (int n) {
this.count = 0;
this.n = n;
list = new LinkedList<Node>();
for (int i=0; i<n; i++){
list.add(new Node(list));
}
}
... the rest of Gossip functions ...
}
Since I’m used to C++ I am not sure how it works here and whether this will work like a pointer and each Node will have a full list or will each Node will only have a list with the Nodes created before it and itself. Also, I don’t need to change the list on the program, just to read from it, but it’s interesting, will a change that one Node does in the list will affect all other Nodes’s lists?
There is only one list of nodes and all the nodes have references to this single list.
This is because in the Node constructor the assignment
this.list=list;doesn’t create a copy of the object – it simply makesthis.listthe same aslist, but remember they both are references (on the stack) to the object (on the heap).Therefore, if you change the list through one of the nodes, all other nodes will see the change.