Java cannot add an object to a list without common

I have these classes.

public class Flight {
    public List<FlightOffer> flightOffers;
}

public class Hotel<T> {
    public List<HotelOffer> hotelOffers;
    public T address
}

public class FlightOffer extends BaseOffer{
}

public class HotelOffer extends BaseOffer{
}

public class BaseOffer{
    public String id;
}

flightOffers and hotelOffers return the list.

Flight flightObject = new Flight();
flightObject.flightOffers.add(new BaseOffer()); // not working 
//(add (FlightOffer) List  cannot be applied to (BaseOffer))

Hotel hotelObject = new Hotel<String>();
hotelObject.hotelOffers.add(new BaseOffer()); // working

but if I transform Flightinto Flight<T>his work, why?

+4
source share
2 answers

List<FlightOffer> flightOffersIt clearly defines what you can add to the list: instances FlightOffer. flightOffers.add(new BaseOffer());therefore, it cannot work, since a is BaseOffernot FlightOffer.

So why does it work hotelOffers.add(new BaseOffer());? Since you disable generic type checks using the original type Hotelin Hotel hotelObject = new Hotel<String>();.

, : . , - , " " .

Edit:

, JLS ( 4.8):

, .

, Hotel , , .. hotelOffers , raw List, ( hotelObject.hotelOffers.add("I'm not a hotel offer");)

+9

BaseOffer () List FlightOffer ().

https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Flight flightObject = new Flight();
flightObject.flightOffers.add(new FlightOffer());    // that correct
+1

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


All Articles