- data :- It is the data, which is present in the node.
- next :- It is used to link the current node to the next node. It is used for keeping track of next node.
- prev :- It links the current node to previous node. It is used for keeping track of previous node.
public class Node {
public int data;
public Node next;
public Node prev;
public Node(final int data) {
this.data = data;
}
}
But, the above definition has a problem. The above class has data variable of int-type. If we need a data of string-type then we will have to create another class for it.
To solve this issue, we can use java-generics to create generic version of above class.
Like this
public class Node<T> {
public T data;
public Node next;
public Node prev;
public Node(final T data) {
this.data = data;
}
}
Now, we will have to mention the data-type while creating Node.
Like this.
Node<Integer> nodeInt = new Node<>(12);
Node<String> nodeString = new Node<>("Anurag");
Node<Boolean> nodeBoolean = new Node<>(false);
Notice the use of diamond operator <> on the right side of equal= operator. This diamond operator is necessary, otherwise compiler will give you below warning.
Note: Node.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.Now, we can print data to check, it is working or not.
System.out.println(nodeInt.data); System.out.println(nodeString.data); System.out.println(nodeBoolean.data);Output
12 Anurag false