多维数组的Java序列化 [英] Java serialization of multidimensional array

查看:24
本文介绍了多维数组的Java序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在java中序列化二维数组?

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

如果没有,我希望将 3x3 2D 数组转换"为向量向量.

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?

谢谢!

推荐答案

Java 中的数组是可序列化的 - 因此 Arrays of Arrays 也是可序列化的.

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);
        }
    }
}

输出:

Before serialization
1
2
3
4
After serialization
1
2
3
4

这篇关于多维数组的Java序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆