Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

java - StackOverFlowError when initializing constructor for a list

I'm confused about why I keep getting a java.lang.StackOverFlow error when I try to write a constructor for MyArrayList, a personal version of the arraylist class in java. I know StackOverFlow errors happen when there is a recursive call, but that doesn't appear to be the case for the code I have written? Can anybody help explain why I'm getting this error?

This is my code, I've included all of the constructors I have written, but the first MyArrayList() is the one that the error indicates in the compiler.

public class MyArrayList<T> {

private int capacity;
private int size;
private T[] data;
**private MyArrayList<T> test;**

private T[] createArrayOfSize(int size)
{
    T[] newArray = (T[]) new Object[size];
    return newArray;

}


**public MyArrayList() {

    this.test = new MyArrayList();

  }**

 public MyArrayList (int initialCapacity) {

   test.data = createArrayOfSize(initialCapacity);

  }

 public MyArrayList(List<T> items) {


     for (int i = 0; i < items.size(); i++) {

       test.data[i] = items.get(i);

   }

 }

Apologies for the slightly crappy formatting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
public MyArrayList() {

    this.test = new MyArrayList();

  }

This bad boy is giving you the problem. Whenever you use "new" operator, a call to the object's constructor is made. Now, inside your constructor you are using "new" again. This new will again call your MyArrayList constructor (which again uses new). this goes on recursively until there is no space left on Stack. So you get StackOverflowError


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...