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

报错: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();

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

2、在内部类前面加上static

static class ListNode{
		int value;
		ListNode next;
		ListNode(int val){
			this.value = val;
			this.next = null;
		}
	}

总的代码:

public class _141_环形链表 {
	
	class ListNode{
		int value;
		ListNode next;
		ListNode(int val){
			this.value = val;
			this.next = null;
		}
	}
	
	public boolean hasCycle(ListNode head) {
		if(head == null || head.next == null) {
			return false;
		}
		ListNode fast = head.next;
		ListNode slow = head;
		while(fast != null && fast.next != null) {
			if(fast == slow) {
				return true;// 快慢相遇 说明肯定有环
			}
			fast = fast.next;
			slow = slow.next;
		}
		return false;
	}
	
	public static void main(String[] args) {
	
	_141_环形链表.ListNode node = new _141_环形链表().new ListNode(3);
		
	}

}

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值