今天在編譯Java程序時遇到如下問題:
No enclosing instance of type PrintListFromTailToHead is accessible. Must qualify the allocation with an enclosing instance
of type PrintListFromTailToHead (e.g. x.new A() where x is an instance of PrintListFromTailToHead).
源代碼為:
1 public class PrintListFromTailToHead { 2 3 public static void main(String[] args) { 4 ListNode one = new ListNode(1); 5 ListNode two = new ListNode(2); 6 ListNode three = new ListNode(3); 7 one.next = two; 8 two.next = three; 9 10 ArrayList<Integer> result = printListFromTailToHead(one); 11 12 System.out.println("結果是:" + result); 13 } 14 15 class ListNode { 16 17 public int val; 18 public ListNode next; 19 20 public ListNode() { 21 22 } 23 24 public ListNode(int val) { 25 this.val = val; 26 } 27 } 28 29 public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { 30 31 Stack<Integer> stack = new Stack<Integer>(); 32 while (listNode != null) { 33 stack.push(listNode.val); 34 listNode = listNode.next; 35 } 36 37 ArrayList<Integer> arrayList = new ArrayList<Integer>(); 38 while (!stack.isEmpty()) { 39 arrayList.add(stack.pop()); 40 } 41 return arrayList; 42 } 45 }
問題解釋:
代碼中,我的ListNode類是定義在PrintListFromTailToHead類中的內部類。ListNode內部類是動態的內部類,而我的main方法是static靜態的。
就好比靜態的方法不能調用動態的方法一樣。
有兩種解決辦法:
第一種:
將內部類ListNode定義成靜態static的類。
第二種:
將內部類ListNode在PrintListFromTailToHead類外邊定義。
兩種解決方法:
第一種:
1 public class PrintListFromTailToHead { 2 3 public static void main(String[] args) { 4 ListNode one = new ListNode(1); 5 ListNode two = new ListNode(2); 6 ListNode three = new ListNode(3); 7 one.next = two; 8 two.next = three; 9 10 ArrayList<Integer> result = printListFromTailToHead(one); 11 12 System.out.println("結果是:" + result); 13 } 14 15 static class ListNode { 16 17 public int val; 18 public ListNode next; 19 20 public ListNode() { 21 22 } 23 24 public ListNode(int val) { 25 this.val = val; 26 } 27 }
第二種:
1 public class PrintListFromTailToHead { 2 3 public static void main(String[] args) { 4 ListNode one = new ListNode(1); 5 ListNode two = new ListNode(2); 6 ListNode three = new ListNode(3); 7 one.next = two; 8 two.next = three; 9 } 10 11 public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { 12 13 Stack<Integer> stack = new Stack<Integer>(); 14 while (listNode != null) { 15 stack.push(listNode.val); 16 listNode = listNode.next; 17 } 18 19 ArrayList<Integer> arrayList = new ArrayList<Integer>(); 20 while (!stack.isEmpty()) { 21 arrayList.add(stack.pop()); 22 } 23 return arrayList; 24 } 25 } 26 27 class ListNode { 28 29 public int val; 30 public ListNode next; 31 32 public ListNode() { 33 34 } 35 36 public ListNode(int val) { 37 this.val = val; 38 } 39 }