将项目添加到列表时出现 java.lang.StackOverflowError

标签 java stack-overflow

尝试将项目添加到列表并打印它们,它编译,但我收到运行时错误,其中存在堆栈溢出错误。这是错误打印出来的内容:

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/

相关文章:

java - saveWebArchive() 不适用于 Android 4.0.3

java - 初始化类的正确方法和堆栈溢出错误

java - 使用 Mapstruct 映射具有双向关系的对象

java - 在 Java 中获取 StackOverFlowError

java - 如何正确使用Reflector Class.cast()?

java - 未报告的异常/this() 需要是第一个语句

java - Android - 从 AsyncTask doInBackground 函数返回整数值

java - 每 20-30 秒更新 Android 小部件的最佳方法 : Handler, 服务或警报?

c++ - 堆栈溢出使用 libzip 创建存档

c# - 为什么这个 Linq 代码总是抛出 System.StackOverflowException?