java 多维数组的Java序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1467193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java serialization of multidimensional array
提问by littleK
Is it possible to make a 2D array in java serializable?
是否可以在 Java 可序列化中制作 2D 数组?
If not, i am looking to "translate" a 3x3 2D array into a Vector of Vectors.
如果没有,我希望将 3x3 2D 数组“转换”为向量向量。
I have been playing around with vectors, and I am still unsure of how to represent that. Can anyone help me?
我一直在玩矢量,但我仍然不确定如何表示它。谁能帮我?
Thanks!
谢谢!
回答by brabster
Arrays in Java are serializable - thus Arrays of Arrays are serializable too.
Java 中的数组是可序列化的——因此数组的数组也是可序列化的。
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

