vibhu kapoor
vibhu kapoor

Reputation: 71

What does node class do in LinkedList class

I am trying to understand how is Java creating nodes i.e. making linked list.So I was checking the LinkedList.java file and I saw a inner node class in linked list class so is this inner node class responsible for actually creating the nodes?

Also when we use this class will we say that object created is for LinkedList Class or for Node Class?

 public class LinkedList<E>
  extends AbstractSequentialList<E>
  implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  {

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;
    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

P.S It is not a duplicate I am trying to understand what is node class doing in the built in LinkedList class which is a double linked list .In the other question they are creating a new singly linked list

Upvotes: 1

Views: 6108

Answers (3)

m4ktub
m4ktub

Reputation: 3121

The innner Node class is not responsible for creating the nodes. It is the node, or actually it represents a node in the linked list. Since items can be anything and the LinkedList wants to link the items (know what is before and what is next each item) it needs the Node abstraction to keep the item and that information.

enter image description here

So LinkedList creates the nodes and connects them. It keeps a pointer to the first and last of those nodes to manage the connections and avoid going in circles when iterating.

Upvotes: 1

KDP
KDP

Reputation: 1481

A linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list is comprises of the data and a reference to the next node and previous node. The last node has a reference to null.

Each element in a linked list is node,which actually holds the data ,previous and next references.

Since the linked list supports reference to the next element we need to have a node which holds data and references as well.

refer Linked List

Upvotes: 1

Tamil Maran
Tamil Maran

Reputation: 291

This kind of implementation is mainly because of preservation of the Node within a LinkedList or increased encapsulation.

Basically Inner classes (here Node class) are used especially when that class has no other use other than using inside another single class.

for example, In this implementation Node is declared as an inner class because the node can exist only in a linked list. without linked list a single node will be of no use.

And this Node class can only be instantiated right after instantiation of linked list. Thus, this supports the concept that No node can exist without a linked list.

So typically this LinkedList and Node are bound together so that Node couldnt exist without creating a LinkedList

Upvotes: 1

Related Questions