我根据EPI的书从头开始在Java中实现了链表。但是,这在创建列表节点时是一个错误。
我的代码是
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);
}
}
这个错误是
Example.java:19: error: non-static variable this cannot be referenced from a static context
p1 = new ListNode<Integer>(123, null);
^
1 error
当我稍微修改它时,它会起作用。
public static class ListNode<T> {
public T data;
public ListNode<T> next;
ListNode(T data, ListNode<T> next) {
this.data = data;
this.next = next;
}
}
但是为什么我应该添加静态?
您不能从静态访问非静态变量,但是可以从非静态访问静态。您的主要方法是静态的,这就是为什么您有一个错误。阅读更多有关静态和非静态之间的区别的信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句