gpt4 book ai didi

java - 包含多个对象的 ArrayList 的序列化,不保存对象状态

转载 作者:太空狗 更新时间:2023-10-29 15:08:10 25 4
gpt4 key购买 nike

我似乎不明白为什么序列化保存和恢复对象的列表,而不是它们的状态。显示列表,但不显示对象中包含的标题。对象类实现 Serializable。

对象序列化(“c”):

arrayList.add ( c );
String fileName = "testFile";

try {
FileOutputStream fos = this.openFileOutput ( fileName, Context.MODE_PRIVATE );
ObjectOutputStream os = new ObjectOutputStream ( fos );
os.writeObject ( arrayList );
fos.close ();
os.close ();
} catch ( Exception ex ) {
ex.printStackTrace ();
}
}

反序列化:

    FileInputStream fis = this.openFileInput ( fileName );
ObjectInputStream ois = new ObjectInputStream ( fis );
arrayList = ( ArrayList<TestObject> ) ois.readObject ();
ois.close ();
return arrayList;

将对象添加到适配器:

    for ( TestObject c : arrayList ) {
adapter.add ( c );
}

编辑:TestObject 类的一部分:

public class TestObject implements Serializable {

private String mName;

@Override
public String toString () {
return mName;
}

public String getName () {
return mName;
}

public void setName ( String name ) {
mName = name;
}

最佳答案

是的,它也对我有用检查

public class SerializationIssue {
private static final String fileName = "testFile";

public static void main(String[] args) {
TestObject object1= new TestObject();
TestObject object2=new TestObject();
object1.setName("object1");
object2.setName("object2");

List<TestObject> list=new ArrayList<TestObject>();
list.add(object1);
list.add(object2);

serializeList(list);
ArrayList<TestObject> deserializedList=desializeDemo();
System.out.println(deserializedList.get(0).getName());

}

private static ArrayList desializeDemo() {
ArrayList<TestObject> deserializedList;
try
{
FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedList= (ArrayList<TestObject>) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return null;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return null;
}
return deserializedList;
}

private static void serializeList(List<TestObject> list) {
// TODO Auto-generated method stub

try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream ( fos );
os.writeObject ( list );
fos.close ();
os.close ();
} catch ( Exception ex ) {
ex.printStackTrace ();
}

}
}

TestObject bean

public class TestObject implements Serializable{

/**
* serial version.
*/
private static final long serialVersionUID = 1L;
String name;
public TestObject(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

输出:对象1

关于java - 包含多个对象的 ArrayList 的序列化,不保存对象状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19741376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com