StackOverFlowError when initializing constructor for a list

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

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

提交回复
热议问题