泛型:ArrayList of ?在 Java 中扩展 ISomeInterface [英] Generic: ArrayList of ? Extends ISomeInterface in Java

查看:30
本文介绍了泛型:ArrayList of ?在 Java 中扩展 ISomeInterface的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下代码中遇到了一些问题.

I'm having some trouble in the following code.

public ArrayList<? extends IEvent> getEventsByDateRange(DateTime minStartTime,  DateTime minEndTime) 
{
    ArrayList<? extends IEvent> returnedEvents = new ArrayList<GoogleEvent>();
    returnedEvents.add(new GoogleEvent());
    return (returnedEvents);
}

这会为returnedEvents.add(new GoogleEvent()); line of code"返回以下编译错误:

This return the following compilation error for the "returnedEvents.add(new GoogleEvent()); line of code":

类型中的add(capture#1-of ? extends IEvent)方法ArrayList 不适用于参数 (GoogleEvent)

The method add(capture#1-of ? extends IEvent) in the type ArrayList is not applicable for the arguments (GoogleEvent)

GoogleEvent 类的声明如下:

public class GoogleEvent implements IEvent {...}

我知道在 Java 中使用泛型有一些棘手的部分,因此是通配符,但我似乎无法弄清楚这一点.

I know there are some tricky parts using generics in Java, thus the wild-cards but I can't seem to figure this out.

谢谢.

推荐答案

你为什么不写:

public List<IEvent> getEventsByDateRange(DateTime minStartTime, DateTime minEndTime)
{
    List<IEvent> returnedEvents = new ArrayList<IEvent>();
    returnedEvents.add(new GoogleEvent());
    return returnedEvents;
}

这篇关于泛型:ArrayList of ?在 Java 中扩展 ISomeInterface的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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