SortedSet,Arrays,Serializable的序列化问题

我在这个过程之前有这个:

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

然后在我的另一部分

 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(new Comp()); Collections.addAll(resultSet, rm); 

为什么我得到ClassCastException?

最后,我让它以这种方式工作:

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

对不起; 我忽略了使用no-arg toArray()调用。

请注意,重载的toArray(T[])方法将数组作为参数。

通过使用此表单,您可以控制数组的组件类型,它将按预期工作。

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