【发布时间】:2017-09-28 12:27:01
【问题描述】:
我正在编写代码以将要序列化的对象列表传输到文件中并返回。问题是当我第一次序列化文件时,使用默认构造函数而不是第二个构造函数来实例化对象。
换句话说,输出带有默认值:
0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]
但应该是:
1234 Robert Smith 07-05-1980 [UCLA]
2345 Donald Trump 07-05-1980 [UCLA]
3456 Barack Obama 07-05-1980 [UCLA]
这是我的主要方法:
public static void main(String[] args) throws IOException, ClassNotFoundException {
// ArrayList list
ArrayList<Student> al = new ArrayList<Student>();
Date d = new Date(80, 5, 7);
Student s = new Student("Robert", "Smith", 1234, d, "UCLA");
Student s2 = new Student("Donald", "Trump", 2345, d, "UCLA");
Student s3 = new Student("Barack", "Obama", 3456, d, "UCLA");
al.add(s);
al.add(s2);
al.add(s3);
// serialization test
FileOutputStream fileOut = new FileOutputStream("StudentList.dat");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(al);
out.close();
fileOut.close();
// deserialization test
FileInputStream fileIn = new FileInputStream("StudentList.dat");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<Student> a2 = (ArrayList<Student>) in.readObject();
in.close();
fileIn.close();
System.out.println(a2.size());
for (Student i : a2) {
System.out.println(i);
} // for
} // main
谢谢
编辑:添加学生类
package edu.uga.cs1302.gui;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
@SuppressWarnings({ "serial", "rawtypes", "deprecation", "unchecked" })
public class Student extends Person implements Serializable {
private String collegeName;
/*
* public Student() { super(); collegeName = null; } // constructor
**/
public void setC(String c) {
collegeName = c;
} // set college
public String getC() {
return collegeName;
} // get college
public Student(String fName, String lName, int n, Date d, String college) {
super(fName, lName, n, d);
collegeName = college;
} // second constructor
public String toString() {
return super.toString() + " [" + collegeName + "]";
} // to string
} // class
【问题讨论】:
-
显示您的
Student课程。 -
@shmosel 添加了它
-
你可能想看看link
-
发布
Person类。 -
@SaurabhShirodkar Shirodakar 我想通了。我没有在 Person 类中实现 Serializable 。感谢您的链接。
标签: java list object serialization constructor