Let’s say I have a list of objects called “Node” inside of this -> Iterable allNodes.
Let’s say I iterated through all the nodes in allNodes and added them to its own list like so:
Iterable<Node> allNodes = dataManager.getAllNodes();
List<Node> copyOfAllNodes;
for(Node node : allNodes) {
copyOfAllNodes.add(node);
}
Does the copy become a reference or is it a copy that doesn’t affect the original list?
It will become just a reference. When you perform:
You are inserint
nodethat is an object intocopyAllNodes.If you want a copy of the object you have other approaches. One of the approaches could be
close, that is basically implement theCloneableinterface and exposeclonemethod in order to copy the object, so you could do something like:And this would be a copy that you could modify without any reflection on the copied object. Is good to remember that the default clone method does just a shallow copy of the object.
From documentation: