Java 中的二维数组是否可以序列化?
如果没有,我希望将 3x3 二维数组“转换”为 vector 的 vector 。
我一直在研究 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
关于多维数组的Java序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1467193/