Java解决No enclosing instance of type PrintListFromTailToHead is accessible问题的两种方案
今天在编译Java程序时遇到如下问题:
NoenclosinginstanceoftypePrintListFromTailToHeadisaccessible.Mustqualifytheallocationwithanenclosinginstance
oftypePrintListFromTailToHead(e.g.x.newA()wherexisaninstanceofPrintListFromTailToHead).
源代码为:
publicclassPrintListFromTailToHead{
publicstaticvoidmain(String[]args){
ListNodeone=newListNode(1);
ListNodetwo=newListNode(2);
ListNodethree=newListNode(3);
one.next=two;
two.next=three;
ArrayList<Integer>result=printListFromTailToHead(one);
System.out.println("结果是:"+result);
}
classListNode{
publicintval;
publicListNodenext;
publicListNode(){
}
publicListNode(intval){
this.val=val;
}
}
publicstaticArrayList<Integer>printListFromTailToHead(ListNodelistNode){
Stack<Integer>stack=newStack<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
ArrayList<Integer>arrayList=newArrayList<Integer>();
while(!stack.isEmpty()){
arrayList.add(stack.pop());
}
returnarrayList;
}
}
问题解释:
代码中,我的ListNode类是定义在PrintListFromTailToHead类中的内部类。ListNode内部类是动态的内部类,而我的main方法是static静态的。
就好比静态的方法不能调用动态的方法一样。
有两种解决办法:
第一种:
将内部类ListNode定义成静态static的类。
第二种:
将内部类ListNode在PrintListFromTailToHead类外边定义。
两种解决方法:
第一种:
publicclassPrintListFromTailToHead{
publicstaticvoidmain(String[]args){
ListNodeone=newListNode(1);
ListNodetwo=newListNode(2);
ListNodethree=newListNode(3);
one.next=two;
two.next=three;
ArrayList<Integer>result=printListFromTailToHead(one);
System.out.println("结果是:"+result);
}
staticclassListNode{
publicintval;
publicListNodenext;
publicListNode(){
}
publicListNode(intval){
this.val=val;
}
}
第二种:
publicclassPrintListFromTailToHead{
publicstaticvoidmain(String[]args){
ListNodeone=newListNode(1);
ListNodetwo=newListNode(2);
ListNodethree=newListNode(3);
one.next=two;
two.next=three;
}
publicstaticArrayList<Integer>printListFromTailToHead(ListNodelistNode){
Stack<Integer>stack=newStack<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
ArrayList<Integer>arrayList=newArrayList<Integer>();
while(!stack.isEmpty()){
arrayList.add(stack.pop());
}
returnarrayList;
}
}
classListNode{
publicintval;
publicListNodenext;
publicListNode(){
}
publicListNode(intval){
this.val=val;
}
}
以上所述是小编给大家介绍的Java解决NoenclosinginstanceoftypePrintListFromTailToHeadisaccessible问题的两种方案,希望对大家有所帮助。