3

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?

4 Answers 4

6

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 Collections are themselves Serializable: Use and trust the JDK API!

Sign up to request clarification or add additional context in comments.

2 Comments

OK, Then I perhaps I should change my code and save the customer the arraylist then, but would I load the arraylist just like this: inObjectStream.readObject(customerList) and the be ready to use the arraylist again, and no need to do soemthing else?
@3D-kreativ - I suggest you try it and see rather than asking a "did you really mean that?" style follow-up question.
3

You should use outObjectStream.writeObject(customerList); and let the ObjectInputStream do the job while reading it back.

1 Comment

Hmm, but if I want to load the customerList, how does it "connect" to the customerList that I have in the code, or do I not need to do anything else after that I have loaded the customerList?! Is it enough to just use somethong like: inObjectStream.readObject(customerList); and then just be happy and continue working with the arrayList!? :)
2

Use ArrayList.add(). The number of elements is not required to be known beforehand.

Comments

1

To read objects from a file into a list you need to read it back in the opposite way you wrote it:

readObject(...)

rather than:

writeObject(...)

However, you really wouldn't normally want to save each object separately. One should either save the whole list at one as one object or ideally save it to a more readable format such as CSV, XML or JSON etc.

Writing and Reading objects gets tricky when you start changing your objects (adding new fields etc.).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.