adding a full list of objects to every object in the list in JAVA
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 Node
s 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 Node
s'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 makes this.list
the same as list
, 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.
There is only one list created in new LinkedList<Node>();
per one Gossip
. Later it is passed by reference (pointer like), thus it same list everywhere.
Is the Node
class used outside of the Gossip
class? If not then you might want to consider making Node
a private inner class of Gossip
. That will simplify things because Node
instances can access the list in Gossip
without having to have their own reference to it. You'll have to define the list as final
to do this.
All variables / fields in java that are derived from java.lang.Object are "references" and that is basically exactly the same as a pointer in C++. (Not to be mixed up with C++ references which are also only pointers but with a special semantic) That means int, float and all other primnitives are values and not pointers/references, ofc.
精彩评论