Reputation: 73
Trying to add items to a list and print them, it compiles, but I'm getting a run time error where theres a stack over flow error. this is what the error prints out:
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
This is my code with the methods to adding and print the list.
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;
}
}
Upvotes: 2
Views: 1573
Reputation: 279970
In your class List
, you have a List
instance field that gets initialized at its declaration
public List athletes = new List();
This means that every List
will have a List
which has a List
which has a List
, ad nauseam, causing a StackOverflowError
as they are being constructed.
I'm not sure what you meant to do with that field, since you aren't using it anywhere. Just remove it.
Upvotes: 6