1. Serializing collections
Good news: almost all standard Java collections (for example, ArrayList, HashSet, HashMap and friends) already implement Serializable. This means you can serialize them out of the box, without any extra hassle.
Example:
import java.io.Serializable;
import java.util.ArrayList;
public class MyList extends ArrayList<String> implements Serializable {
// You don't even need to write anything — ArrayList is already Serializable!
}
In practice, you usually serialize standard collections, and everything works without unnecessary fuss.
How to serialize a collection?
To serialize a collection, use the same approach as for any other object:
- Create a collection.
- Write it to a file via ObjectOutputStream.
- Read it back via ObjectInputStream.
Example 1: Serializing ArrayList<String>
import java.io.*;
import java.util.*;
public class SerializeListDemo {
public static void main(String[] args) throws Exception {
// 1. Create a list of strings
List<String> books = new ArrayList<>();
books.add("The Catcher in the Rye");
books.add("Great Expectations");
books.add("The Divine Comedy");
// 2. Save the list to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("books.ser"));
out.writeObject(books);
out.close();
// 3. Read the list back from the file
ObjectInputStream in = new ObjectInputStream(new FileInputStream("books.ser"));
List<String> loadedBooks = (List<String>) in.readObject();
in.close();
// 4. Verify the result
System.out.println("Book list after deserialization:");
for (String book : loadedBooks) {
System.out.println("- " + book);
}
}
}
Output:
Book list after deserialization:
- The Catcher in the Rye
- Great Expectations
- The Divine Comedy
Example 2: Serializing HashSet<Integer>
Set<Integer> numbers = new HashSet<>(Arrays.asList(10, 20, 30, 40));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("numbers.ser"));
out.writeObject(numbers);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("numbers.ser"));
Set<Integer> loadedNumbers = (Set<Integer>) in.readObject();
in.close();
System.out.println("Set after deserialization: " + loadedNumbers);
Example 3: Serializing HashMap<String, Integer>
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 100);
scores.put("Bob", 80);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("scores.ser"));
out.writeObject(scores);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("scores.ser"));
Map<String, Integer> loadedScores = (Map<String, Integer>) in.readObject();
in.close();
System.out.println("Map after deserialization: " + loadedScores);
Important points
Is the order preserved?
- For List (e.g., ArrayList), the element order is always preserved.
- For Set (HashSet), the order is not guaranteed (both before and after serialization).
- For Map (HashMap), the order of key–value pairs is not guaranteed (if you need ordering, use LinkedHashMap).
Empty collections are serialized and deserialized without issues. After deserialization you get an empty list/set/map.
Nested collections (for example, List<List<String>>) are serialized correctly if all nested elements are serializable.
2. Requirements for collection elements
This is where the first serious pitfall often lurks!
All elements of the collection must also be serializable.
If at least one element of the collection does not implement the Serializable interface, serialization of the collection will fail with NotSerializableException. And if the collection is large and the error is buried somewhere inside, hunting down the culprit turns into an entertaining quest.
Example: serializing a collection with a non-serializable object
import java.io.*;
import java.util.*;
class NotSerializableClass {
int value;
public NotSerializableClass(int value) {
this.value = value;
}
}
public class NotSerializableDemo {
public static void main(String[] args) throws Exception {
List<Object> list = new ArrayList<>();
list.add("Hello");
list.add(new NotSerializableClass(123)); // <- Oops!
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("badlist.ser"));
try {
out.writeObject(list); // An exception will be thrown here!
} catch (NotSerializableException e) {
System.out.println("Serialization error: " + e);
}
out.close();
}
}
Result:
Serialization error: java.io.NotSerializableException: NotSerializableClass
What to do?
The solution is simple: all elements of the collection must either be standard types such as String or Integer, or your own classes that implement the Serializable interface. If a class is not serializable, just add implements Serializable to it, and the problem is solved.
3. Specifics of serializing different collections
Is the element order preserved?
- List: Yes, the element order is preserved.
- Set: It depends on the implementation. In HashSet the order is not guaranteed, whereas in LinkedHashSet it is preserved.
- Map: In HashMap the order is not guaranteed; in LinkedHashMap insertion order is preserved.
Demonstration:
List<String> list = Arrays.asList("A", "B", "C");
Set<String> set = new HashSet<>(list);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("coll.ser"));
out.writeObject(list);
out.writeObject(set);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("coll.ser"));
List<String> loadedList = (List<String>) in.readObject();
Set<String> loadedSet = (Set<String>) in.readObject();
in.close();
System.out.println("List: " + loadedList); // always [A, B, C]
System.out.println("Set: " + loadedSet); // could be [A, C, B], etc.
Serializing empty collections
Empty collections serialize without issues. After deserialization you get an empty object of the required type.
Serializing nested collections
You can serialize collections that contain other collections:
List<List<String>> table = new ArrayList<>();
table.add(Arrays.asList("row1-col1", "row1-col2"));
table.add(Arrays.asList("row2-col1", "row2-col2"));
// Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("table.ser"));
out.writeObject(table);
out.close();
// Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("table.ser"));
List<List<String>> loadedTable = (List<List<String>>) in.readObject();
in.close();
System.out.println(loadedTable);
4. Practical example: serializing a collection of objects of your own class
Let’s write a small application for a “virtual library” where we’ll serialize a list of books. The Book class must be serializable!
import java.io.*;
import java.util.*;
class Book implements Serializable {
private static final long serialVersionUID = 1L; // for class version compatibility
String title;
String author;
int year;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
@Override
public String toString() {
return title + " (" + author + ", " + year + ")";
}
}
public class LibraryApp {
public static void main(String[] args) throws Exception {
List<Book> books = new ArrayList<>();
books.add(new Book("The Catcher in the Rye", "J. D. Salinger", 1951));
books.add(new Book("Great Expectations", "Charles Dickens", 1861));
books.add(new Book("The Divine Comedy", "Dante Alighieri", 1320));
// Save the list to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mylibrary.ser"));
out.writeObject(books);
out.close();
// Read the list back
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mylibrary.ser"));
List<Book> loadedBooks = (List<Book>) in.readObject();
in.close();
System.out.println("Books from the file:");
for (Book b : loadedBooks) {
System.out.println("- " + b);
}
}
}
5. Common mistakes when serializing collections
Error #1: NotSerializableException on a collection element. If at least one element of the collection is not serializable, serialization will “fail” with NotSerializableException. For example, if you accidentally added to the collection an object that does not implement Serializable, or forgot to add this interface to your class.
Error #2: Changing a class between serialization and deserialization. If you serialized a collection of objects and then changed the class structure (for example, added or removed fields), an InvalidClassException may occur during deserialization. To avoid this, use the serialVersionUID field in the class.
Error #3: Serializing a collection with transient or static fields. Fields marked transient or static are not serialized. If your objects depend on such fields, after deserialization they will have default values (for example, null or 0).
Error #4: Serializing collections with nested non-serializable objects. If the collection contains nested collections or objects that do not implement Serializable, the error will occur at the deepest level — it is not always immediately clear where to look for the problem. Check all levels of nesting!
Error #5: Performance with large collections. If a collection is very large, serialization can take a lot of time and disk space. In such cases, consider streaming serialization or splitting the collection into parts.
GO TO FULL VERSION