Android上的反序列化数组 [英] Deserializing Arrays on Android

查看:228
本文介绍了Android上的反序列化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个大的应用程序,我发现了一个小细节。这是可能的序列化阵列,并把它们放在一个包。然后把它放在一个意向,并开始活动。但是,在接收端我有经历一个痛苦的2步程序反序列化数组。

I'm currently working on a big app and I found a little Detail. It's possible to serialize Arrays and put them in a bundle. Then put it in a intent and start the activity. But on the receiving end I have to deserialize the array through a painful 2 step procedure.

     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];
     }

什么是我必须经历通过数组循环的原因是什么?

What's the reason that I have to go through looping through the array?

推荐答案

的问题是,如果你有对象的数组你投以数组 MyObj中,编译器将不得不通过和验证类的每个阵列中的项目的,让演员成为 MyObj中[] 。 Java语言的设计师做了一个决定,这样做,并迫使程序员写出来。例如:

The issue is that if you have an array of Object that you cast to be an array of MyObj, the compiler would have to go through and verify the class of each of the items in the array to allow the cast to be MyObj[]. The Java language designers made a decision to not do that and to force the programmer to write it out. For example:

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语言的力量,你自己做循环。

So the Java language forces you to do the loop yourself.

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];
}

您可以使用阵列类(使用 System.arraycopy()本机方法)来轻松做这样的:

You can use the Arrays class (which uses the System.arraycopy() native method) to easily do this:

MyObj[] data3 = Arrays.copyOf(temp, temp.length, MyObj[].class);

请参阅:<一href=\"http://stackoverflow.com/questions/1018750/how-to-convert-object-array-to-string-array-in-java\">How为对象数组转换为Java中字符串数组

这篇关于Android上的反序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆