Java错误:No enclosing instance of type _141_环形链表 is accessible. Must qualify the allocation with an en

Bertha 。 2023-01-17 08:58 238阅读 0赞

报错:No enclosing instance of type _141_环形链表 is accessible. Must qualify the allocation with an enclosing instance of type _141_环形链表 (e.g. x.new A() where x is an instance of _141_环形链表).

报错描述:
没有封闭的实例类型_141_环形链表是可访问的。必须有资格分配一个封闭的实例类型_141_环形链表(例如x.new的(),x是一个实例_141_环形链表)。

最近在刷LeetCode的时候,在刷题过程出现这样一个问题。查了一下相关资料,原来我原先定义的内部类是动态的,然而main方法是静态的,静态方法不能直接调用动态方法,要先创建外部类然后才可以调用内部动态方法,或者是直接在内部类前面加上static,也可。

总结一下:静态方法main不能直接调用内部类,因为内部类是动态的(public class开头的),在main中调用的两种方法:

1、new外部类,再new内部类中的动态方法

EqualsObject.Transport obj1 = new EqualsObject().new Transport();

  1. _141_环形链表.ListNode node = new _141_环形链表().new ListNode(3);

2、在内部类前面加上static

  1. static class ListNode{
  2. int value;
  3. ListNode next;
  4. ListNode(int val){
  5. this.value = val;
  6. this.next = null;
  7. }
  8. }

总的代码:

  1. public class _141_环形链表 {
  2. class ListNode{
  3. int value;
  4. ListNode next;
  5. ListNode(int val){
  6. this.value = val;
  7. this.next = null;
  8. }
  9. }
  10. public boolean hasCycle(ListNode head) {
  11. if(head == null || head.next == null) {
  12. return false;
  13. }
  14. ListNode fast = head.next;
  15. ListNode slow = head;
  16. while(fast != null && fast.next != null) {
  17. if(fast == slow) {
  18. return true;// 快慢相遇 说明肯定有环
  19. }
  20. fast = fast.next;
  21. slow = slow.next;
  22. }
  23. return false;
  24. }
  25. public static void main(String[] args) {
  26. _141_环形链表.ListNode node = new _141_环形链表().new ListNode(3);
  27. }
  28. }

参考:
https://blog.csdn.net/sunny2038/article/details/6926079

发表评论

表情:
评论列表 (有 0 条评论,238人围观)

还没有评论,来说两句吧...

相关阅读