我正在开发一个大应用程序,我发现了一个小细节.可以序列化Arrays并将它们放在一个包中.然后将其置于意图中并开始活动.但是在接收端,我必须通过痛苦的两步程序对阵列进行反序列化.
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];
}
Run Code Online (Sandbox Code Playgroud)
我必须经历数组循环的原因是什么?
问题是,如果你有一个数组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];
Run Code Online (Sandbox Code Playgroud)
所以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];
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Arrays该类(使用本System.arraycopy()机方法)轻松执行此操作:
MyObj[] data3 = Arrays.copyOf(temp, temp.length, MyObj[].class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1656 次 |
| 最近记录: |