user3055864
user3055864

Reputation:

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.

Upvotes: 0

Views: 741

Answers (2)

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 5

Radnyx
Radnyx

Reputation: 324

You're constructing a MyArrayList inside your MyArrayList constructor. This means that it will construct Array Lists forever (allocating more and more memory) until the stack can't hold it any longer.

If you only want one test of 'MyArrayList', then make it 'static' as in:

static MyArrayList test;

That way it will only be declared once in all instances of your class, however, you'll still get a recursion error because when you construct it, test will construct itself. To fix that you need to check for null:

public MyArrayList() {
    if (test == null)
        test = new MyArrayList();
}

This is an example of what 'TheLostMind' stated. The "Singleton pattern".

Upvotes: 2

Related Questions