初始化列表的构造函数时出现 StackOverFlowError [英] StackOverFlowError when initializing constructor for a list

查看:34
本文介绍了初始化列表的构造函数时出现 StackOverFlowError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试为 MyArrayList 编写构造函数时,为什么我一直收到 java.lang.StackOverFlow 错误,我很困惑,MyArrayList 是 Java 中 arraylist 类的个人版本.我知道在递归调用时会发生 StackOverFlow 错误,但我编写的代码似乎并非如此?有人可以帮助解释为什么我会收到此错误吗?

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?

这是我的代码,我已经包含了我编写的所有构造函数,但第一个 MyArrayList() 是错误在编译器中指示的那个.

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.

推荐答案

public MyArrayList() {

    this.test = new MyArrayList();

  }

这个坏孩子给你出了问题.每当您使用new"运算符时,都会调用对象的构造函数.现在,在您的构造函数中,您再次使用new".这个 new 将再次调用您的 MyArrayList 构造函数(它再次使用 new).这递归地进行,直到堆栈上没有剩余空间.所以你得到 StackOverflowError

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

这篇关于初始化列表的构造函数时出现 StackOverFlowError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆