Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic: ArrayList of ? Extends ISomeInterface in Java

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

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

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

The declaration of the class GoogleEvent is as follows:

public class GoogleEvent implements IEvent {...}

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

Thanks.

like image 531
Mortalus Avatar asked Mar 24 '26 10:03

Mortalus


2 Answers

Why don't you write:

public List<IEvent> getEventsByDateRange(DateTime minStartTime, DateTime minEndTime)
{
    List<IEvent> returnedEvents = new ArrayList<IEvent>();
    returnedEvents.add(new GoogleEvent());
    return returnedEvents;
}
like image 155
KARASZI István Avatar answered Mar 27 '26 01:03

KARASZI István


You don't need to use ? extends IEvent because by using only IEvent, Java will dynamically bind the GoogleEvent class. It's polymorphism.

like image 20
Iulius Curt Avatar answered Mar 27 '26 01:03

Iulius Curt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!