I implement a linked list from scratch in java according to the book of EPI. However this is an error when creating list nodes.
My code is
public class Example {
class ListNode<T> {
public T data;
public ListNode<T> next;
ListNode(T data, ListNode<T> next) {
this.data = data;
this.next = next;
}
}
public static void main(String[] args) {
System.out.println("Hello world.");
ListNode<Integer> p1 = new ListNode<Integer>(123, null);
}
}
This error is
Example.java:19: error: non-static variable this cannot be referenced from a static context
p1 = new ListNode<Integer>(123, null);
^
1 error
It works when I revise it a little bit.
public static class ListNode<T> {
public T data;
public ListNode<T> next;
ListNode(T data, ListNode<T> next) {
this.data = data;
this.next = next;
}
}
But why I should add static?