-1

I was starting on linked list program in java but there was a problem struck on my mind that if pointers are not allowed in java then how are linked list created in java.(I am familiar with linked list in C++). I have got this class LinkedListto create the node

public class LinkedList { 

Node head; // head of list 

// Linked list Node. 
// This inner class is made static 
// so that main() can access it 
static class Node { 

    int data; 
    Node next; 

    // Constructor 
    Node(int d) 
    { 
        data = d; 
        next = null; 
    } 
} 

The code works but i am not getting as how the reference is being created at the next node.

abby
  • 33
  • 5
  • This code doesn't create any references; it declares two fields of reference type `Node head;` and `Node next;`, and the `Node` constructor assigns `null` to one of those fields. – kaya3 Feb 28 '20 at 18:36
  • 1
    FYI all Objects in Java exist in the heap (okay, or in the string constants pool) and the stack accesses them through references, which is another name for a pointer – ControlAltDel Feb 28 '20 at 18:37
  • 1
    The difference between Java and C for example, is that pointers in Java are strongly typed. – ControlAltDel Feb 28 '20 at 18:39
  • 1
    https://dzone.com/articles/java-different-types-of-references – Arvind Kumar Avinash Feb 28 '20 at 18:40

3 Answers3

1

Explicit pointer arithmetics are not available for the Java programmer, pointers are everywhere in Java too.

Actually, Java references are pointers, they were named like that after a series of bad decisions from the developers at Sun, hence creating this great confusion. https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.3.1 (See second sentence)

Also, another great source of confusion is comparing Java references to references (or aliases) from C++ (or many more non-JVM based programming languages). They are nothing alike, Java has got pointers named references and C++ has got both pointers and references.

Toni Nagy
  • 133
  • 2
  • 11
0

Every time you reference an object in Java, you use a reference (a rough approximation of a shared_ptr). Only primitive types (like int) are value types in Java, everything else is internally built on references. So no copy constructors are needed, and no special "pointer type" is needed.

So if you declare Node next, next is a reference to an object, not a copy of it.

A reasonable linked list could like so:

class Node<T> {
  T value;
  Node<T> next;

  public Node(T value, Node<T> next) {
    this.value = value;
    this.next = next;
  }
}

Node<String> list = new Node("This", new Node("is", new Node("it.", null)));
9000
  • 39,899
  • 9
  • 66
  • 104
0

You need an setNext method node

public void setNext(Node n) {
  next = n;
}

Then

Node n1 = new Node(1);
Node n2 = new Node(2);
n1.setNext(n2);
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80