簡體   English   中英

將項目添加到列表時出現java.lang.StackOverflowError

[英]java.lang.StackOverflowError while adding items to list

嘗試將項目添加到列表並打印它們時,它會進行編譯,但是我遇到了運行時錯誤,其中出現了堆棧溢出錯誤。 這是錯誤輸出的內容:

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 ,該List具有一個List ,這是個惡心,在構造它們時會引起StackOverflowError

我不確定您打算對該領域做什么,因為您沒有在任何地方使用它。 只需將其刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM