[英]StackOverFlow error - from instantiating my object class
I am trying to make a class in Java that builds an object of type Action
which holds three ints and returns it to my other class in the array history
, where history
is an array of type Action
. 我试图用Java创建一个类,该类构建一个Action
类型的对象,该对象具有三个int并将其返回到数组history
中的另一个类,其中history
是Action
类型的数组。 When it is called I immediately get an endless loop; 当它被调用时,我立即得到一个无限循环。 hence the stack overflow. 因此堆栈溢出。
Error - I printed 1 line, it goes on... 错误-我打印了1行,然后继续...
Exception in thread "main" java.lang.StackOverflowError
at sudokugame.Action.<init>(Action.java:7)
Class: 类:
public class Action {
Action a;
public Action(int i, int o, int p){
a = new Action(i,o,p);
}
public void setAction(int n, int b, int c){
}
public Action getAction(){
return a;
}
}
Your constructor calls itself recursively forever. 您的构造函数会永远递归地调用自身。 A sure way to overflow a stack :) 溢出堆栈的肯定方法:)
public Action(int i, int o, int p){
//why do you do this?
a = new Action(i,o,p);
}
Maybe what you really wanted to do was just store i,o and p in the class instance? 也许您真正想做的只是将i,o和p存储在类实例中?
public class Action {
int i;
int o;
int p;
public Action(int i, int o, int p){
this.i = i;
this.o = o;
this.p = p;
}
...
}
(edit: see other answer for fuller example) (编辑:有关完整示例,请参见其他答案 )
Try doing it this way: 尝试通过这种方式:
public class Action {
int i;
int o;
int p;
public Action(int i, int o, int p){
this.i = i;
this.o = o;
this.p = p;
}
public void setAction(int n, int b, int c){
this.i = i;
this.o = o;
this.p = p;
}
public Action getAction(){
return this;
}
}
The problem is here: 问题在这里:
a = new Action(i,o,p);
You are invoking the constructor again for a new instance inside the constructor of the class itself. 您正在为类本身的构造函数中的新实例再次调用构造函数。 Since each subsequent call to the constructor will create a new constructor call there is no way for the stack to unwind, therefore creating a stack overflow. 由于每次对构造函数的后续调用都会创建一个新的构造函数调用,因此堆栈无法展开,因此会导致堆栈溢出。
您实例化类本身。
Does your Action class really need to hold on to a reference to another Action? 您的Action类是否真的需要保留对另一个Action的引用?
Action a;
Specifically, is this line necessary? 具体来说,这行是必要的吗? What are you using it for? 您用它做什么?
确保您的构造函数具有递归调用。
命令设计模式是一种处理情况的方法,其中您希望拥有执行的操作的历史记录,以便可以撤消操作等。
构造函数有递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.