CPP"s Node*
is equivalent to java's Node
, and I'm pretty sure C#'s Node
as well. In java, all primitives are the direct value. The primitives are int
, long
, short
, byte
, char
, double
, float
, and boolean
. These are passed directly, by value: If you call a method passing 5
, 5 is pushed onto the stack. If the method you invoke changes their value, the caller can't tell.
But aside from that hardcoded list of primitives, all other types are called references which is just java-ese for pointers - except in java, you can't do pointer arithmatic. at all. You can't ask for 'the memory location 5 higher than where-ever this object lives', like you can do in C.
Here's a trivial example:
class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Hello!");
System.out.println(list);
example1(list);
System.out.println(list);
example2(list);
System.out.println(list);
}
static void example1(List<String> in) {
list.add("World!");
}
static void example2(List<String> in) {
in = new ArrayList<String>();
in.add("Bye!");
}
}
This will print:
[Hello!]
[Hello!, World!]
[Hello!, World!]
example1 never changes the variable (The reference), it merely 'dereferences it' (follows the pointer), thus the changes you make are observed in the caller.
But example2 has no effect on main's list variable: It reassigns the variable (makes a new object and then updates its reference to point at this new object). example1's list doesn't change; its pointer doesn't change.
It's like treasure maps: Everybody has a copy of the treasure map, but not of the treasure. in.add
is like: "Follow the map, open the treasure chest, put a new item in". in = new ArrayList
is: "Make a new treasure chest, bury it in the sand, wipe out this treasure map, and now write the location of this newly buried treasure chest on it". If I have a copy of your map, if you follow your copy and add to the treasure then I'll see that if I later follow my map. But if you make an entirely new map, then whatever you do to the treasure at your new location is never going to be noticed by me.
This matches C++'s behaviour.... at least, for Node*
. Not for Node
.