I am new to generics and I am trying out to make a linked list.
Here is the Code for Node_ class.
public class Node_<T> {
private int index;
private T data;
private Node_<T> next;
public Node_() {
}
public Node_(T data, int index) {
this.data = data;
this.index = index;
next = null;
}
public void set(T data, int index) {
this.data = data;
this.index = index;
this.next= null;
}
public void display() {
System.out.println(this.data.toString());
}
public void setindex(int index) {
this.index = index;
}
public void setData(T data) {
this.data = data;
}
public Node_<T> getNext() {
return next;
}
public boolean hasNext() {
if (next != null) return true;
else return false;
}
public int getIndex() {
return this.index;
}
}
and linked list class.
public class LinkList<T> {
private int total = 0;
private Node_<T> start;
private Node_<T> end;
private Node_<T> ptr;
public LinkList() {
}
public LinkList(T data) {
start = new Node_<T>(data, 0);
end = start;
ptr = start;
total++;
}
public void add(T data) {
if (start == null) {
start = new Node_<T>(data, 0);
end = start;
ptr = start;
total++;
} else {
end.set((T) data,(int) total);
total++;
end = end.getNext();
}
}
public void displayAt(int index) {
if (start != null) {
ptr = start;
do {
if (ptr.getIndex() == index)
ptr.display();
} while (ptr.hasNext());
}
else
System.out.println("No Element found");
}
public void displayAll() {
if (start != null) {
ptr = start;
do {
ptr.display();
} while (ptr.hasNext());
}
else
System.out.println("No Element Present");
}
}
The following code in Main class
public class Main {
public static void main(String[] args) {
LinkList<Integer> list = new LinkList<Integer>(25);
list.displayAll();
for (int i = 0; i < 11; i++) {
list.add((Integer) i);
}
list.displayAll();
}
}
I am getting the following error and i cant figure out the problem.
25
Exception in thread "main" java.lang.NullPointerException
at LinkList.add(LinkList.java:26)
at Main.main(Main.java:8)
Any suggestion where am I going wrong.