I wonder how I should do to read objects from a list if I don’t know how many object there are? To save is easier because than I use the number of objects that I have in the ArrayList where I 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 thought was to use something similar to load all objects in the file and add them one after one to the ArrayList after it has been cleared. But as I wrote, it’s not possible when I don’t know the number of object inside the file. Any ideas how I can solve this in simple way?
Your design is flawed: You should be serializing the List to file, not each Customer object. Then you would just deserialize the whole List.
After deserializing you will have a new instance of the list. If you absolutely must load the customers into your list, use
customerList.addAll(list);All of the common
Collectionsare themselvesSerializable: Use and trust the JDK API!