在我的程序中,我想使用堆栈保存一些状态。 但是堆栈中的所有对象总是相同的(最好是我输入)。 这是我的保存代码:
public void saveState(){
state.setMatrix(temp.clone()); //temp is int[][]
state.setScore(score); //score is int
State newgaGameState = new State(state); //copy consructor
stack.push(newgaGameState);
}
我想我需要复制状态,因为堆栈保存了引用。 我需要怎么做? 我做错了什么?
感谢。
答案 0 :(得分:0)
您要向state
添加信息,然后保存gameState
。如果这不是拼写错误,那么你似乎并没有真正保存任何新内容。
答案 1 :(得分:0)
您需要使用deep copy。因此,您可以执行以下操作之一:
答案 2 :(得分:-3)
使用ObjectOutputStream
和ObjectInputStream
;
的writeObject
FileOutputStream fout = new FileOutputStream(file-full-path);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(your-object);
oos.close();
读取对象
FileInputStream fin = new FileInputStream(file-full-path);
ObjectInputStream ois = new ObjectInputStream(fin);
Your-Class yourObject = (Your-Class) ois.readObject();
ois.close();