英文:
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<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.
答案1
得分: 3
java.lang.StackOverflowError意味着堆栈已经溢出。
你有一个递归调用,没有停止条件。
我认为在你的方法public TestList()
中,你想要类似这样的内容:tList = new ArrayList<Test>
。
英文:
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<Test>
;
答案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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论