开发者

Serialize list of employees in java

I have a simple employee class:

class Employee {

    private int     id;
    private String  firstName;
    private String  lastName;
    private String  streetAddress;
    private String  city;
    private String  state;
    private String  zip;
    pr开发者_运维技巧ivate String  cellularPhoneNumber;
    private String  homePhoneNumber;

    public Employee(int id, String firstName, String lastName, String streetAddress, String city, String state, String zip, String cellularPhoneNumber, String homePhoneNumber) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.streetAddress = streetAddress;
        this.city = city;
        this.state = state;
        this.zip = zip;
        this.cellularPhoneNumber = cellularPhoneNumber;
        this.homePhoneNumber = homePhoneNumber;
    }
}

How could I go about serializing multiple employees to a file? I know how to serialize one object, but how could I have multiple ones?

Could somebody point me in the right direction or provide a sample of serializing multiple objects? Would I be better off using a database like SQLite?

Much thanks in advanced.


The collections in java.util are Serializable. So if you make your Employee class implement Serializable, then put your employees in an ArrayList, then you can serialize the list and it will save the employees.

HSQLDB and H2 are in-memory databases implemented in Java that may be good alternatives to SQLite (meaning easier to use from a Java program). For general learning purposes using a database is a more practical skill, serializing things is not something I do a lot (when my code does use serialized classes the actual serialization is left up to the environment, such as when storing things in an HttpSession).


  1. add(..) the objects to a List - for example an ArrayList
  2. serialize the list

As for your SQLite question - I can't tell. Generally, you shouldn't use serialization as a database storage, but if your application is simple, it should suffice.


List<Employee> e = new ArrayList<Employee>() {{

add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));

}};


Employee implements Serializable {

.....
}

?


I would recommend to go for serialization using Jackson , JSON .

The benefit is that after serializing, you can atleast see your Data. Java Serialization is limiting in many aspects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜