堆栈溢出错误:在另一个类中实例化对象时

huangapple go评论73阅读模式
英文:

StackOverflowError when instantiating an object in another class

问题

Testing.java:

public static void main(String[] args) {
     TestList t = new TestList();
}

TestList.java:

public class TestList extends ArrayList<Test> {

     protected TestList tList;

     public TestList() {
          tList = new TestList();
     }
}

I also have a Test.java class that works fine. The issue is in the main method, when the TestList t object is instantiated, I get a StackOverflow Error: Exception in thread "main" java.lang.StackOverflowError

I'm not sure HOW to fix this because the object has to be a TestList.

英文:

Testing.java:

public static void main(String[] args) {
     TestList t = new TestList();
}

TestList.java

public class TestList extends ArrayList&lt;Test&gt; {

     protected TestList tList;

     public TestList() {
          tList = new TestList();
     }
}

I also have a Test.java class that works fine. The issue is in the main method, when the TestList t object is instantiated, I get a StackOverflow Error: Exception in thread "main" java.lang.StackOverflowError

I'm not sure HOW to fix this because the object has to be a TestList.

答案1

得分: 3

java.lang.StackOverflowError意味着堆栈已经溢出。
你有一个递归调用,没有停止条件。
我认为在你的方法public TestList()中,你想要类似这样的内容:tList = new ArrayList&lt;Test&gt;

英文:

java.lang.StackOverflowError means that the stack has been burst.
You have a recursive call, without a stop condition.
I think in your method public TestList(), you want something like this tList = new ArrayList&lt;Test&gt;;

答案2

得分: 1

因此,看起来你正在在构造函数内部创建一个自身的元素。这将导致它无限地创建自身的实例。

当你调用 new TestList() 时,它会调用 new TestList(),然后又调用 new TestList(),如此反复,直到出现堆栈溢出错误。

如果你需要一个对象拥有其自身的实例,我建议你考虑使用单例模式。不过,基于这似乎是一个列表,我不确定这是否适合解决你的问题。你能否更详细地说明一下你究竟想要做什么?

英文:

So it seems as if you are creating an element of itself within its constructor. This will result in it infinitely creating instances of itself.

When you call new TestList() it then calls new TestList() which then calls new TestList() and on and on until you receive the stack overflow error.

If you need to have an object have an instance of itself I would look into using a singleton. Although, based on this being a list I am not sure that is what is best suited to solve your problem. Can you shed a little more light on exactly what you're trying to do?

huangapple
  • 本文由 发表于 2020年9月29日 21:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64121022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定