Some question on java basics,
the below function returns an object of Node type
class DS{
public Node getNode(int index){
return nodeList.get(index);
}
}
public void test1(){
DS ds = new DS();
Node node = ds.getNode(3);
// will the change in node variable(of test1()) change the actual Node object in ds?
// Is there a simple way to create a copy to prevent source node's data modification?
}
Thanks in advance.
The
getNode()method on the DS class returns a reference to the node stored innodeList. As such, if yourNodeclass can be mutated (via setter methods or direct access to its fields), then yes, your code intest1will change the underlying (and now shared) Node reference.If you want to “disconnect” the returned node from the node in your datastore, then you can clone it first. Your node class will need to implement
Cloneableand override theclone()method. If you have only primitives in Node, then you can simply do:If you have other objects in Node, then the default clone operation will only make a shallow copy, and you will need to make your clone method more extensive so that it makes deep copies. From the Javadoc for Object.clone():
The change to your DS class will be: