我需要澄清如何保存对另一个对象有引用的对象的状态?
假设我有以下类对象需要保存和恢复:
public class ObjectA implements Serializable{
private List<ObjectB> mObjectBList;
}
public clas ObjectB implements Serializable {
// some other members here
private ObjectA mParent;
}
以下是在片段中调用保存和恢复的代码:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("ObjectA", mObjectA);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mObjectA = (mObjectA) savedInstanceState.getSerializable("ObjectA");
}
}
问题:
我不清楚当一个对象被保存为Serializable时会发生什么,所以请帮助我理解Android如何区分何时实例化一个新对象以及它何时会重现一个实际的引用。
答案 0 :(得分:0)
是。但List
不是Serializable
。例如,将List
更改为ArrayList
。
一切正常。 Java序列化适用于循环引用。 Here是类似的问题。
我认为没有问题。
我使用以下代码进行测试。
public class MainActivity extends AppCompatActivity {
private ObjectA mObjectA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mObjectA = (ObjectA) savedInstanceState.getSerializable("ObjectA");
// check mObjectA == mObjectA.getObjectBList().get(0).getParent();
} else {
mObjectA = new ObjectA();
ArrayList<ObjectB> list = new ArrayList<>();
list.add(createB());
list.add(createB());
list.add(createB());
list.add(createB());
list.add(createB());
mObjectA.setObjectBList(list);
}
}
private ObjectB createB() {
ObjectB objectB = new ObjectB();
objectB.setParent(mObjectA);
return objectB;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("ObjectA", mObjectA);
}
}
public class ObjectA implements Serializable {
private ArrayList<ObjectB> mObjectBList;
public void setObjectBList(ArrayList<ObjectB> objectBList) {
mObjectBList = objectBList;
}
public ArrayList<ObjectB> getObjectBList() {
return mObjectBList;
}
}
public class ObjectB implements Serializable {
// some other members here
private ObjectA mParent;
public void setParent(ObjectA parent) {
mParent = parent;
}
public ObjectA getParent() {
return mParent;
}
}