StackOverFlowError when initializing constructor for a list

后端 未结 2 878
春和景丽
春和景丽 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

提交回复
热议问题