尝试将项目添加到列表并打印它们,它编译,但我收到运行时错误,其中存在堆栈溢出错误。这是错误打印出来的内容:
Exception in thread "main" java.lang.StackOverflowError
at List.<init>(List.java:5)
at List.<init>(List.java:9)
at List.<init>(List.java:9) <----- this line is repeated quite a few times
这是我的代码,包含添加和打印列表的方法。
public class List {
private AthleteNode front;
public List(){
front = null;
}
public List athletes = new List();
//add athlete to the end of the list
public void add(Athlete a){
AthleteNode node = new AthleteNode (a);
AthleteNode current; //temp node to iterate over the list
if(front == null)
front = node;//adds the first element
else{
current = front;
while (current.next !=null)
current = current.next;
current.next=node;
}
}
最佳答案
在你的类 List
中,你有一个 List
实例字段,它在声明时被初始化
public List athletes = new List();
这意味着每个 List
都会有一个 List
,它有一个 List
,它有一个 List
,广告恶心,在构造它们时导致 StackOverflowError
。
我不确定你打算用那个字段做什么,因为你没有在任何地方使用它。只需将其删除即可。
关于将项目添加到列表时出现 java.lang.StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064820/