컬렉션 프레임워크는 자바에서 데이터를 저장하고 관리하기 위한 중요한 도구입니다. 이러한 컬렉션은 종종 네트워크 통신 또는 영속적인 데이터 저장을 위해 직렬화되어야 할 수 있습니다. 직렬화는 객체의 상태를 바이트 스트림으로 변환하여 저장하거나 전송하는 프로세스를 의미합니다.
자바에서는 java.io.Serializable
인터페이스를 구현하여 객체를 직렬화할 수 있습니다. 이 인터페이스를 구현하면 해당 객체의 상태를 저장하고 복원할 수 있습니다.
컬렉션 프레임워크의 대부분의 클래스는 이미 Serializable
인터페이스를 구현하고 있어서 직렬화할 수 있습니다. 예를 들어, ArrayList
과 HashMap
은 자동으로 직렬화할 수 있는 컬렉션 클래스입니다.
다음은 ArrayList
을 직렬화하는 예시입니다.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class SerializationExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
try {
FileOutputStream fileOut = new FileOutputStream("list.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(list);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in list.ser");
} catch (Exception e) {
e.printStackTrace();
}
}
}
위 코드에서는 ArrayList
객체를 생성하고 몇 가지 요소를 추가합니다. 그리고 ObjectOutputStream
을 사용하여 객체를 파일에 직렬화합니다. 직렬화된 객체는 “list.ser”라는 파일에 저장됩니다.
직렬화된 컬렉션을 다시 복원하려면 다음과 같이 코드를 작성할 수 있습니다.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class DeserializationExample {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("list.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<String> list = (ArrayList<String>) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized data: ");
for (String item : list) {
System.out.println(item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
위 코드에서는 “list.ser” 파일에서 직렬화된 ArrayList
객체를 읽어와서 복원합니다. 복원한 객체를 통해 원래의 데이터를 다시 사용할 수 있습니다.
컬렉션 프레임워크의 직렬화는 데이터의 안정적인 저장 및 전송을 가능하게 합니다. Serializable
인터페이스를 활용하여 자바 컬렉션을 직렬화하는 방법을 알고 있다면, 더욱 효율적인 데이터 관리를 할 수 있습니다.