How can I store an arraylist of custom objects?

后端 未结 3 2017
悲&欢浪女
悲&欢浪女 2020-12-28 18:49

I have created an arraylist that is made up of custom objects. Basically the user will create a class and every time a class is created, a new Lecture (my custom object) is

3条回答
  •  鱼传尺愫
    2020-12-28 19:09

    I use a class in a Weather app I'm developing...

    public class RegionList extends ArrayList {} // Region implements Serializeable
    

    To save I use code like this...

    FileOutputStream outStream = new FileOutputStream(Weather.WeatherDir + "/RegionList.dat");
    ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream);
    objectOutStream.writeInt(uk_weather_regions.size()); // Save size first
    for(Region r:uk_weather_regions)
        objectOutStream.writeObject(r);
    objectOutStream.close();
    

    NOTE: Before I write the Region objects, I write an int to save the 'size' of the list.

    When I read back I do this...

    FileInputStream inStream = new FileInputStream(f);
    ObjectInputStream objectInStream = new ObjectInputStream(inStream);
    int count = objectInStream.readInt(); // Get the number of regions
    RegionList rl = new RegionList();
    for (int c=0; c < count; c++)
        rl.add((Region) objectInStream.readObject());
    objectInStream.close();
    

提交回复
热议问题