Tech Interview Guide
Master Your Java Skills and Ace the Interview
Introduction to Serialization in Java
In Java, serialization is a mechanism that allows converting an object into a byte stream so that it can be easily stored or transferred over a network. This is particularly useful when working with objects that need to be saved in files or sent across a network. Serialization allows objects to be stored in a persistent form, which can later be deserialized back into their original state.
When working with List objects, such as ArrayList
or LinkedList
, serialization allows these collections to be saved or transmitted as well. In this article, we will explore how to serialize a List in Java using both standard and custom serialization techniques.
What is Serialization?
Serialization is the process of converting an object into a byte stream. This byte stream can then be written to a file, sent over a network, or saved in any other form of persistent storage. Deserialization is the reverse process, where the byte stream is converted back into the original object.
In Java, an object is serializable if its class implements the Serializable
interface. This interface is a marker interface, meaning it does not contain any methods. Its sole purpose is to indicate that objects of the class can be serialized.
The Serializable
interface is located in java.io
package. Here’s a simple example of a class implementing the Serializable
interface:
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
How to Serialize a List in Java
Now that we understand what serialization is, let’s move on to how you can serialize a List
in Java. The process of serializing a List
is very similar to serializing any other object. As long as the List
contains elements that are serializable, the entire list can be serialized.
Step 1: Implement Serializable Interface
Just like any other object, the elements inside the List
need to implement the Serializable
interface. For example, if the list contains Person
objects (as in our previous example), the Person
class must implement Serializable
.
Step 2: Serialize the List
You can use ObjectOutputStream
to write the List
object to a file or an output stream. Here’s an example that demonstrates serializing a list of Person
objects:
import java.io.*;
import java.util.*;
public class ListSerializationExample {
public static void main(String[] args) {
// Creating a List of Person objects
List people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
try {
// Creating an ObjectOutputStream to write the list to a file
FileOutputStream fileOut = new FileOutputStream("people.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
// Writing the list to the stream
out.writeObject(people);
out.close();
fileOut.close();
System.out.println("List has been serialized to people.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
In this example, we first create a list of Person
objects, then serialize the list to a file called people.ser
. The ObjectOutputStream
is responsible for writing the serialized object to the file.
Step 3: Deserialize the List
To deserialize the list, you use the ObjectInputStream
class, which converts the byte stream back into the original List
object.
import java.io.*;
import java.util.*;
public class ListDeserializationExample {
public static void main(String[] args) {
try {
// Creating an ObjectInputStream to read the list from the file
FileInputStream fileIn = new FileInputStream("people.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
// Reading the list from the stream
List people = (List) in.readObject();
in.close();
fileIn.close();
// Printing the deserialized list
for (Person person : people) {
System.out.println(person.getName() + " - " + person.getAge() + " years old");
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we read the serialized List
from the file people.ser
and cast it back to a List
of Person
objects. We then print the details of each Person
in the list.
Handling Serialization Exceptions
When serializing and deserializing objects, several exceptions can occur. Some common exceptions include:
- java.io.NotSerializableException: This exception is thrown if an object in the list does not implement the
Serializable
interface. - java.io.InvalidClassException: This occurs when the version of the class has changed after serialization (e.g., adding/removing fields).
To prevent these issues, always ensure that all objects within the list are serializable, and be cautious about changing class structures after serialization.