How to serialize and deserialize a ArrayList?

1. Introduction

This article is final article on Complete Guide to ArrayList series. In this article we will discuss how to serialize and deserialize an ArrayList.

2. Content

Serialization would work if and only if the elements inserted in ArrayList are serializable. Means that this object’s class implements a Serializable interface. 

Serialization means we can transform an Object into a stream of data which can be stored as a file or in a database or can be transmitted over the network and can be used later.

3. Serialize

final String serializedFileName = "namesSerialized";
List<String> names = new ArrayList<>();
names.add("John");
names.add("Jane");
names.add("Jack");
serialize(names, serializedFileName);


private void serialize(List<String> names, String serializedFileName) {
  try {
    FileOutputStream fos = new FileOutputStream(serializedFileName);
    ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
    oos.writeObject(names);
    oos.close();
    fos.close();
  } catch (IOException ioException) {
    ioException.printStackTrace();
  }
}

The file would look like this :

4. Deserialize

private List<String> deserialize(String serializedFileName) {
  try {
    FileInputStream fis = new FileInputStream(serializedFileName);
    ObjectInputStream ois = new ObjectInputStream(fileInputStream);
    ArrayList<String> namesDes = (ArrayList<String>) ois.readObject();
    ois.close();
    fis.close();
    return namesDes;
  } catch (FileNotFoundException e2) {
    e2.printStackTrace();
  } catch (ClassNotFoundException | IOException e) {
    e.printStackTrace();
  }
  return Collections.emptyList();
}

5. Serialize a custom class

In order to serialize a custom class that you write you need to implement java.io.Serializable interface.

If you don’t implement java.io.Serializable interface than you will get this exception

java.io.NotSerializableException: com.justamonad.tutorials.collections.Name
	at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1193)
	at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:353)
	at java.base/java.util.ArrayList.writeObject(ArrayList.java:865)

Let us create a class called Name that holds two values i.e. firstName and lastName.

public class Name implements Serializable, Comparable<Name> {

	private static final long serialVersionUID = -7470957962267746723L;

	private final String firstName;
	private final String lastName;

	private static final String FIRST_NAME_ERR = "invalid firstName";
	private static final String LAST_NAME_ERR = "invalid lastName";

	public Name(String firstName, String lastName) {
		Objects.requireNonNull(firstName, FIRST_NAME_ERR);
		Objects.requireNonNull(lastName, LAST_NAME_ERR);

		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String firstName() {
		return firstName;
	}

	public String lastName() {
		return lastName;
	}
	
	@Override
	public int compareTo(Name that) {
		int compare = this.firstName.compareTo(that.firstName);
		if(compare == 0) {
			compare = this.lastName.compareTo(that.lastName);
		}
		return compare;
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((firstName == null) 
									? 0 : firstName.hashCode());
		result = prime * result + ((lastName == null) 
									? 0 : lastName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Name other = (Name) obj;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		return true;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Name [firstName=");
		builder.append(firstName);
		builder.append(", lastName=");
		builder.append(lastName);
		builder.append("]");
		return builder.toString();
	}

}

Serialization code

final String serializedFileName = "namesClassSerialized";
List<Name> names = new ArrayList<>();
names.add(new Name("Arya", "Stark"));
names.add(new Name("Ned", "Stark"));
names.add(new Name("Jon", "Snow"));
serializeNames(names, serializedFileName);

List<Name> deserializedNames = deserializeNames(serializedFileName);
Assert.assertTrue(names.equals(deserializedNames));

private void serializeNames(List<Name> names, String serializedFileName) {
  try {
    FileOutputStream fos = new FileOutputStream(serializedFileName);
    ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
    oos.writeObject(names);
    oos.close();
    fos.close();
  } catch (IOException ioException) {
    ioException.printStackTrace();
  }
}

The file would look like this :

6. Deserialize a custom class

private List<Name> deserializeNames(String serializedFileName) {
  try {
    FileInputStream fis = new FileInputStream(serializedFileName);
    ObjectInputStream ois = new ObjectInputStream(fileInputStream);
    ArrayList<Name> namesDes = (ArrayList<Name>) ois.readObject();
    ois.close();
    fis.close();
    return namesDes;
  } catch (FileNotFoundException e2) {
    e2.printStackTrace();
  } catch (ClassNotFoundException | IOException e) {
    e.printStackTrace();
  }
  return Collections.emptyList();
}

7. Conclusion

In this article we saw how we can serialize and deserialize an ArrayList object and store it in a file.

Leave a Reply

Your email address will not be published. Required fields are marked *