Can I serialize an array directly, or do I have to wrap it in an object first?

Tim Rohaly

Although it's not obvious, arrays in Java are objects; they have methods you can invoke (toString(), equals(), etc.) and contain instance variables (length). The unnamed array superclass also implements Serializable, so all array types can be serialized directly, without any further work from the programmer, as shown in the following code example:

public class Test {
    public static void main(String[] args) throws Exception {

        // Serialize an int[]
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.ser"));
        out.writeObject(new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});

        // Deserialize the int[]
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.ser"));
        int[] array = (int[]) in.readObject();

        // Print out contents of deserialized int[]
        System.out.println("It is " + (array instanceof Serializable) + " that int[] implements Serializable");
        System.out.print("Deserialized array: " + array[0]);
        for (int i=1; i<array.length; i++) {
            System.out.print(", " + array[i]);

The usual restrictions apply, of course - if you have an array of objects, the contents of that array must also be serializable in order for the array to be successfully serialized.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.