List <t>上的通用类型兼容性错误,T为接口</t>

时间:2012-10-24 13:39:16

标签: java

我有这个java代码:

tgia = new ThumbsGalleryAdapter(this, profilePositionsOverlay.items);

我收到此错误:

  

构造函数ThumbsGalleryAdapter(SharePositionMapActivity,List)未定义   SharePositionMapActivity.java   /com.shopzeus.android.majorforms.activity.MainActivity/src/com/shopzeus/android/majorforms/activity   第114行Java问题

ThumbsGalleryAdapter的构造函数是:

public ThumbsGalleryAdapter(Activity aActivity, List<ThumbsGalleryItem> aItems)

profilePositionsOverlay.items的类型:

List<SharedPositionMapItem>

名称ThumbsGalleryItem指的是界面:

public interface ThumbsGalleryItem {
    public String getTitle();
    public String getRemotePath();
}

最后,SharedPositionMapItem是一个实现ThumbsGalleryItem的类:

private static class SharedPositionMapItem extends OverlayItem implements ThumbsGalleryItem

问题是,当然:为什么List<SharedPositionMapItem>List<ThumbsGalleryItem>不兼容?因为SharedPositionMapItem implements ThumbsGalleryItem,我希望它们兼容。解决方案是什么?

2 个答案:

答案 0 :(得分:5)

public ThumbsGalleryAdapter(Activity aActivity, List<? extends ThumbsGalleryItem> aItems)

有关详细信息,请参阅: http://codeidol.com/java/javagenerics/Subtyping-and-Wildcards/The-Get-and-Put-Principle/ 还有这个 Explanation of the get-put principle

答案 1 :(得分:5)

泛型本质上是invarant,这意味着List<Integer>不是List<Object>

的子类型

您需要的是任何类型的ThumbsGalleryItem 列表,您可以在下面声明

 List<? Extends ThumbsGalleryItem>

您可以阅读有关wildcards

的更多信息