StackOverFlowError when initializing constructor for a list

后端 未结 2 879
春和景丽
春和景丽 2020-12-12 07:53

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.

相关标签:
2条回答
  • 2020-12-12 08:20
    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

    0 讨论(0)
  • 2020-12-12 08:20

    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".

    0 讨论(0)
提交回复
热议问题