ArrayList 不能转换为扩展 ArrayList 的自定义类 [英] ArrayList cannot be cast to custom class extending ArrayList

查看:23
本文介绍了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 会将您的 extras 变成包裹,它会通过检查每个对象类型来做到这一点(因为,正如我所说,它不记得您想要它的方式).

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 打包是这样的:

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

如果您想保留列表,您需要创建一个可序列化的类,并且不会扩展数组列表但会将它包含在其中.

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天全站免登陆