【发布时间】:2015-08-05 04:20:21
【问题描述】:
java中的二维数组是否可以序列化?
如果没有,我希望将 3x3 2D 数组“转换”为向量的向量。
我一直在玩向量,但我仍然不确定如何表示它。谁能帮帮我?
谢谢!
【问题讨论】:
标签: java arrays serialization vector
java中的二维数组是否可以序列化?
如果没有,我希望将 3x3 2D 数组“转换”为向量的向量。
我一直在玩向量,但我仍然不确定如何表示它。谁能帮帮我?
谢谢!
【问题讨论】:
标签: java arrays serialization vector
Java 中的数组是可序列化的 - 因此数组的数组也是可序列化的。
但是,它们包含的对象可能不是,因此请检查数组的内容是否可序列化 - 如果不是,请进行序列化。
这是一个使用整数数组的示例。
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
【讨论】: