Example: Custom Serialization of a Collection
What You'll Learn
You'll learn how to implement writeObject and readObject for a custom collection class to serialize only essential data efficiently, avoiding redundant internal structures.
The Problem with Default Serialization
When you create a custom collection class, default serialization might save unnecessary internal data structures—like backing arrays with empty slots, hash table buckets, or rebalancing metadata. This wastes space and exposes implementation details.
The solution: Override writeObject and readObject to serialize only the actual elements, then reconstruct your collection's internal structure during deserialization.
How It Works
Think of it like packing a backpack for a trip. You don't pack the entire closet organizer system—just the clothes themselves. On arrival, you reorganize them into drawers using whatever system makes sense at the destination.
Custom Collection Example
import java.io.*;
import java.util.*;
public class IntList implements Serializable {
private static final long serialVersionUID = 1L;
private transient int[] elements; // Don't serialize the array
private int size;
public IntList() {
elements = new int[10];
size = 0;
}
public void add(int value) {
if (size == elements.length) {
elements = Arrays.copyOf(elements, size * 2);
}
elements[size++] = value;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // Write 'size'
// Write only the actual elements, not empty slots
for (int i = 0; i < size; i++) {
out.writeInt(elements[i]);
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject(); // Read 'size'
// Reconstruct array and populate it
elements = new int[size];
for (int i = 0; i < size; i++) {
elements[i] = in.readInt();
}
}
}
Notice we marked elements as transient, then manually wrote only size elements—not the entire backing array.
Key Takeaway: Custom serialization lets you serialize only meaningful data (the elements) while skipping internal structures, making your serialized form smaller, faster, and implementation-independent.