18

Is it possible to make a 2D array in java serializable?

If not, i am looking to "translate" a 3x3 2D array into a Vector of Vectors.

I have been playing around with vectors, and I am still unsure of how to represent that. Can anyone help me?

Thanks!

1 Answer 1

28

Arrays in Java are serializable - thus Arrays of Arrays are serializable too.

The objects they contain may not be, though, so check that the array's content is serializable - if not, make it so.

Here's an example, using arrays of ints.

public static void main(String[] args) {

    int[][] twoD = new int[][] { new int[] { 1, 2 },
            new int[] { 3, 4 } };

    int[][] newTwoD = null; // will deserialize to this

    System.out.println("Before serialization");
    for (int[] arr : twoD) {
        for (int val : arr) {
            System.out.println(val);
        }
    }

    try {
        FileOutputStream fos = new FileOutputStream("test.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(twoD);

        FileInputStream fis = new FileInputStream("test.dat");
        ObjectInputStream iis = new ObjectInputStream(fis);
        newTwoD = (int[][]) iis.readObject();

    } catch (Exception e) {

    }

    System.out.println("After serialization");
    for (int[] arr : newTwoD) {
        for (int val : arr) {
            System.out.println(val);
        }
    }
}

Output:

Before serialization
1
2
3
4
After serialization
1
2
3
4
Sign up to request clarification or add additional context in comments.

3 Comments

Hm, okay. My multidimensional array holds nothing but integers, but I'm glad to know that the array itself is indeed serializable, thanks...
Works with ints for me - not sure why you're seeing a problem. Good luck!
This didn't work for me because I had to close the object and file streams. This may help you if the code isn't working for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.