本文介绍了泛型: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)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:26