Peter said:
The following two examples pass an object into a function, please
explain why the first example "WILL" lose the reference and second
"DONT"?
import javax.swing.tree.DefaultMutableTreeNode;
public class tt{
public static void main(String[] args)
{
String str="1234";
ddd(str);
System.out.println("yyy=" + str);
}
static private void ddd(String t)
{
t ="3455";
}
}
This method gets as parameter a copy (named t) of the reference to a String
object (with the content "1234"). It changes that reference to point to a
*different* String object (newly created with the content "3455"),
but neither the original object nor the original reference to it (named str)
are changed. Since both the new reference and the new object exit only within
the method and are lost after completing it, the method effectively does
nothing.
import javax.swing.tree.DefaultMutableTreeNode;
public class tt{
public static void main(String[] args)
{
DefaultMutableTreeNode yyy =
new DefaultMutableTreeNode(new Integer(1234));
ddd(yyy);
System.out.println("yyy=" + yyy.getUserObject());
}
static private void ddd(DefaultMutableTreeNode t)
{
t.setUserObject("3455");
}
Here the method is given a copy (named t) of the reference to an object
of class DefaultMutableTreeNode which internally contains a reference
(the name of which we don't know) to an object of class Integer that
has the value 1234.
The method then calls a method of the tree node object which causes it
to change its internal reference to instead point to a newly-created
String object with the value "3455".
When the method ends, the reference t is lost, but the original reference
yyy still points to the same tree node object. Then its getUserObject
method is called and returns the internal reference, which now points at
the new String object. This String's contents are then displayed.
The Integer object, which is not anymore references anywhere, is lost.