In my original code, I’m adding nodes to a tree. My goal is to somehow get access to the last node that I added in the tree (my idea was to create another object that will point to the last object (node in my original example)).
public class RandomSubClass
{
int firstNum;
}
import java.util.LinkedList;
public class RandomClass
{
LinkedList<RandomSubClass> myListOfObjects = new LinkedList<RandomSubClass>();
void addItem(int firstNum, RandomSubClass toBeReturned)
{
RandomSubClass o1 = new RandomSubClass();
o1.firstNum = firstNum;
myListOfObjects.add(o1);
// Here I was thinking that 'toBeReturned' will get same address as
// 'o1', and by changing 'toBeReturned' (in main), values in 'o1' change
//
toBeReturned = o1;
// This following commented code worked,
// but I can't use it in my original code.
//
// The reason I can't use it is because when I add a node to a tree,
// I start at the root and trace the new node's way to a new leaf,
// which makes it hard to do (simply) that.
//
//toBeReturned.firstNum = firstNum;
//myListOfObjects.add(toBeReturned);
}
}
public class Main
{
public static void main(String[] args)
{
RandomClass myList = new RandomClass();
RandomSubClass r1 = new RandomSubClass();
RandomSubClass r2 = new RandomSubClass();
myList.addItem(1, r1);
myList.addItem(2, r2);
// I would like to do that, and see changes in the node in 'myList'
//
r1.firstNum = 10;
r2.firstNum = 20;
}
}
I want to check something about the node after I add it to the tree, and if it satisfies some condition, I want to change a flag for that node.
I can re-trace the node again (starting at root), but my tree might get huge at some point and it will take time. So if I get the address of that node when I add it, and after I check my condition, I can modify the flag at that address, knowing that it will change the flag at that node (last added).
Yes, you can do this. I give you permission. 🙂 But your example code won’t work because Java objects are passed by value, not by reference. That is, when you pass an object to a function, if you reassign that object, it has no effect on the caller. For example:
The output of this function is “Hello”, NOT “Goodbye”. The assignment within the updateString function does not change the value passed in by the caller.
There are (at least) three ways to do what you want.
Method 1: The simplest is to return the new object, rather than updating a parameter:
I prefer this method what I don’t need to have some other return value: it’s clean and simple.
Method 2: Create a global variable and store a handle of the object there. But this method sucks, because globals suck in general. I only mention it to tell you not to do it.
Method 3: Create a wrapper to hold a reference to the object. Then pass the wrapper to the “add” function, which can update the value within the class.