Java – loads objects from a file into ArrayList

I don't know. If I don't know how many objects there are, how should I read objects from the list? Saving is easier because I use the number of objects in ArrayList to store all objects Code like this:

// Save all customer object from customerList
for(int j=0; j < customerList.size(); j++) {
    outObjectStream.writeObject(customerList.get(j));
}

My idea is to use something similar to load all the objects in the file and add them to ArrayList one by one after clearing But as I wrote, this is not possible when I do not know the number of objects in the file What do you think? How can I solve this problem in a simple way?

Solution

Your design is flawed: you should serialize the list as a file instead of every customer object Then you just need to deserialize the entire list

After deserialization, you will have a new instance of the list If you absolutely have to load customers into the list, use customerlist addAll(list);

All common collections are serializable in themselves: use and trust the JDK API!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>