I'm coming from a background in C and C , where I grew pretty comfortable with pointers and references. Now I'm learning Data Structures and Algorithms in Java, and I saw a slide talking about nodes in Linked Lists being structured as so
class Node<E>{
E element;
Node<E> next;
public Node(E o){
element = o;
}
}
Given my background, to me this looks like the next node is contained directly within this node, and there's nothing to clarify that it's a reference (pointer?) to a separate address in memory. I also know at this point that Java doesn't have pass-by-reference at all, which makes this even weirder (from my perspective). So I want to know, how do I tell the difference between variables that hold actual values or objects, and variables that hold references to other values/objects
CodePudding user response:
In Java, unlike C or C , all variables with types that are not primitives are references. In this case, next
is a reference because Node
is an object, not a primitive. element
would also be a reference to another object, unless E
is a primitive. Java's garbage collector handles all the memory management for these references, so you don't need to worry about allocation and freeing the memory for the underlying objects. For example:
Foo bar = new Foo(); // bar is an object of the class Foo
Foo foobar = bar; // all objects are references, so bar and foobar are
// referencing the same underlying memory
int a = 1; // a is an int
int b = a; // the value of a is copied into b, because a is a
// primitive
CodePudding user response:
In Java, variables fall into two categories.
- primitives (
int, short, boolean, char, long, byte, double, float
), - references (everything else).
The type parameter E
can't be a primitive type in this context, so in your code, element
and next
both store references to something. That's why your class succeeds in implementing a linked list.
As for the question of how this works with "pass by value" - argument values passed to a method are either primitives or references, just like the values of any other Java variable. So if your parameter is a reference type, not a primitive; then although you're doing "pass by value", it behaves a little like "pass by reference", insofar as the method being called now has access to the original object, not a copy. Of course, it's not really "pass by reference" because the method that was called can't change what the original variable refers to.
CodePudding user response:
Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable. reference variables are practically always objects in Java. Let's take a look at both of these types with the help of two examples.