Serialization issue with SortedSet, Arrays, an Serializable

房东的猫 提交于 2019-12-29 09:23:11

问题


I have this before the process:

protected void onPostExecute(SortedSet<RatedMessage> result) {
    List<Object> list=Arrays.asList(result.toArray());
    lancon.putExtra("results", list.toArray()); // as serializable
}

then in the other part I have

Object o=this.getIntent().getSerializableExtra("results");
//at this point the o holds the correct value (checked by debugger)
RatedMessage[] rm = (RatedMessage[]) o;// this line hangs out w ClassCastException
resultSet = new TreeSet<RatedMessage>(new Comp());
Collections.addAll(resultSet, rm);

Why I get the ClassCastException?


回答1:


Finally I got it to work this way:

Serializable s = this.getIntent().getSerializableExtra("results");
Object[] o = (Object[]) s;
if (o != null) {
    resultSet = new TreeSet<RatedMessage>(new Comp());
    for (int i = 0; i < o.length; i++) {
        if (o[i] instanceof RatedMessage) {
            resultSet.add((RatedMessage) o[i]);
        }
    }
}



回答2:


I'm sorry; I overlooked the use of the no-arg toArray() call.

Please note that there's overloaded toArray(T[]) method that takes an array as an argument.

By using this form, you can control the component type of the array, and it will work as expected.

protected void onPostExecute(SortedSet<RatedMessage> result) {
  lancon.putExtra("results", result.toArray(new RatedMessage[result.size()]));
}


来源:https://stackoverflow.com/questions/3136922/serialization-issue-with-sortedset-arrays-an-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!