【问题标题】:Can't cast ArrayList class to ArrayList of interface [duplicate]无法将 ArrayList 类转换为接口的 ArrayList [重复]
【发布时间】:2018-05-25 02:13:38
【问题描述】:

代码结构

public interface ListItem
public abstract class Device implements ListItem
public class DeviceList extends ArrayList<Device>
public class ListAdapter extends BaseAdapter{
...
    public ArrayList<ListItem> items;
...
    }

我想将 DeviceList 传递给 ListAdapter,但不能将 DeviceList 转换为 ArrayList。这是为什么呢?

如果Device实现了ListItem,而DeviceList是Device的数组列表,我不应该可以投吗?

我是这样尝试的:

ArrayList<ListItem> list2 = (ArrayList<ListItem>) device_list;

【问题讨论】:

  • devicelist 是 Device 类型,arraylist 是 listitem 类型
  • 是的,但是 Device 实现了 ListItem,所以我应该可以投射它?

标签: java android arraylist casting


【解决方案1】:

这是一个常见的误解。尽管 Device 是 ListItem,但 Device List 不是 ListItems 的 List。 顺便说一句,这已经回答了,例如见How to cast List<Object> to List<MyClass>How do you cast a List of supertypes to a List of subtypes?

【讨论】:

  • 谢谢,我会尽快接受答复[:
猜你喜欢
  • 1970-01-01
  • 2012-07-05
  • 2014-04-30
  • 2019-03-15
  • 2012-08-22
  • 2012-04-25
  • 2014-05-15
  • 2015-07-14
  • 2011-12-09
相关资源
最近更新 更多