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

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

问题描述

我很困惑,为什么我总是收到java.lang.StackOverFlow错误,当我尝试写MyArrayList一个构造函数,Java中的ArrayList类的个人版。我知道,当有一个递归调用StackOverflow的错误发生,但是,这并不似乎是为code我写了呢?任何人可以帮助解释为什么我得到这个错误?

这是我的code,我已经包含了所有我写的构造函数,而是先MyArrayList()是一个错误在编译器指示之一。

 公共类MyArrayList< T> {私人诠释能力;
私人诠释的大小;
私人T []的数据;
**私人MyArrayList< T>测试;**私人T [] createArrayOfSize(INT大小)
{
    T [] newArray =(T [])新对象【尺寸】;
    返回newArray;}
**公共MyArrayList(){    this.test =新MyArrayList();  } ** 公共MyArrayList(INT参数:initialCapacity){   test.data = createArrayOfSize(参数:initialCapacity);  } 公共MyArrayList(列表< T>项目){
     的for(int i = 0; I< items.size();我++){       test.data [I] = items.get(ⅰ);   } }

对于稍微蹩脚的格式道歉。


解决方案

 公共MyArrayList(){    this.test =新MyArrayList();  }

这坏小子所赐你的问题。当你使用新的经营者,该对象的构造函数调用。现在,你的构造函数中使用的是新的一次。这个新将再次拨打您的MyArrayList构造函数(而这又采用了新的)。任其发展下去,直到递归没有留在堆栈空间。所以,你得到的StackOverflowError

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.

解决方案

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

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

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