我目前正在开发一个大型应用程序,我发现了一些细节。序列化数组并将它们放在一个包中是可能的。然后把它放在一个 Intent 中并开始 Activity 。但是在接收端,我必须通过一个痛苦的两步过程来反序列化数组。
MyObj[] data = (MyObj[])bundle.getSerializable("key"); // doesn't work
Object[] temp = (Object[])bundle.getSerializable("key");
MyObj[] data2 = (MyObj[])temp, // doesn't work
MyObj[] data3 = new MyObj[temp.length]; // does work
for(int i = 0; i < temp.length; i++) {
data3[i] = (MyObj)temp[i];
}
我必须遍历数组的原因是什么?
最佳答案
问题是,如果您有一个 Object
数组,您将其转换为 MyObj
数组,编译器将不得不检查并验证类数组中的每个项目都允许转换为 MyObj[]
。 Java 语言设计者决定不这样做,并强制程序员将其写出来。例如:
Object[] objs = new Object[] { "wow", 1L };
// this isn't allowed because the compiler would have to test each object itself
String[] strings = (String[]) objs;
// you wouldn't want an array access to throw the ClassCastException
String foo = strings[1];
因此 Java 语言强制您自己执行循环。
Object[] objs = new Object[] { "wow", 1L };
String[] strings = new String[objs.length];
for (int i = 0; i < objs.length; i++) {
// this can then throw a ClassCastException on this particular object
strings[i] = (String) objs[i];
}
您可以使用 Arrays
类(它使用 System.arraycopy()
native 方法)轻松执行此操作:
MyObj[] data3 = Arrays.copyOf(temp, temp.length, MyObj[].class);
关于java - 在 Android 上反序列化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419028/