How to pass a list of types instead of interfaces in java

I have an event list (interface) and this is what I want to return in my method

public List<Event> getEvents(){ return list;}

Inside the class, I need to initialize the list.

List<EventImpl> list = new ArrayList<EventImpl>();

For some reason, I thought I could do this:

List<Event> list = new ArrayList<EventImpl>();

But it seems like I can't, Do I need some magic for casting in getEvents ()? If so, how is this done?

thank

+4
source share
2 answers

If you want getEvents()to return List<Event>, the easiest way is to create List<Event>in the method first of all:

List<Event> list = new ArrayList<Event>();

The fact that it listwill only consist of instances EventImpldoes not matter.

- (, List<EventImpl> ), List<EventImpl> List<Event>,

List<Event> copy = new ArrayList<Event>(listOfEventImpl);

List<Event> ArrayList<Event> List<EventImpl> ArrayList<EventImpl>. , - , .

( , .)

+2

List<? extends Event>. Java generics List<Event> list = new ArrayList<EventImpl>(); .

, - list.add(new SomeOtherEventImpl()), SomeOtherEventImpl / Event, EventImpl. , , , SomeOtherEventImpl , EventImpl.

+4

Source: https://habr.com/ru/post/1568251/


All Articles