ArrayList无法强制转换为自定义类扩展ArrayList [英] ArrayList cannot be cast to custom class extending ArrayList

查看:171
本文介绍了ArrayList无法强制转换为自定义类扩展ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面提到的课程:

public class JsonHistoryList extends ArrayList<JsonHistory> implements Serializable{}

我希望通过意图传递它

timerService.putExtra(TimerService.ACTIVITY_LIST_ARG, activities);

但我收到后(以下方式)

But after I receive it (way below)

JsonHistoryList temp = (JsonHistoryList) intent.getSerializableExtra(TimerService.ACTIVITY_LIST_ARG);

在我的服务中它给我例外:

in my service it gives me exception:

Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.epstim.captime.jsonmodel.JsonHistoryList

我不明白为什么java无法处理该操作。

I don't understand why java can't handle that operation.

我已经改变了我的服务代码:

I've changed my code in service to:

ArrayList<JsonHistory> temp = (ArrayList<JsonHistory>) intent.getSerializableExtra(TimerService.ACTIVITY_LIST_ARG);
activities.addAll(temp);

它运作良好。

推荐答案

在内部,android将每个额外的内容放在一个特殊的Map中,并且不会记录你想要它的确切位置。

In the internals, android puts every extra in a special Map and doesn't record how exactly you want it parcelled.

在某些时候android会将你的额外内容扁平化为包裹,它会通过检查每个对象类型来实现(因为,正如我所说,它不记得你想要它如何)。

At some point android will flattern your extras into parcel, and it will do so by checking each object type (since, as I said, it doesn't remember how you want it).

Parcel支持writeList和writeSerializable,你的JsonHistoryList也是(可序列化列表和可序列化本身)

Parcel supports both writeList and writeSerializable and your JsonHistoryList is also both (list of serializables and a serialisable itself)

所以android parcelling是这样的:

So android parcelling goes like this:

for (Object object : extras) {
   //... check for other types here
   } else if (object instanceof List) {
     parcel.writeList(object); // This what happens in your case and will be unparcelled into arraylist
   } else if (object instanceof Serializable) {
     parcel.writeSerializable(object); // What you really want, but percelling never will get here
   }
}

如果你想保留列表,你需要创建一个可序列化的类,不会扩展arraylist但会将其包含在内。

If you want to preserve list you need to create a class that will be serializable and won't extend arraylist but will contain it inside.

public class SuperJsonHistory implements Serializable {
  private JsonHistoryList yourList;
  ...
}

因此,如果你想要继承,那么构成优于继承保留类型

So composition over inheritance in case you want to preserve type

这篇关于ArrayList无法强制转换为自定义类扩展ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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