简体   繁体   中英

Casting list of one type with generic to another

I have a 3 classes:

BaseNotification {}

ManagerNotification extends BaseNotification {}

NotificationWrapper<T extends BaseNotification> {
   private T message
}

What a best way to cast List<NotificationWrapper<ManagerNotification>> to List<NotificationWrapper<?>> (or List<NotificationWrapper<? extends BaseNotification>> ) ?

I want to avoid unchecked casting warning also.

Here is an example why you can't widen the type of a generic Type based on your example:

StaffNotifcation extends BaseNotification {}

List<NotificationWrapper<ManagerNotification>> list = new ArrayList<>();

list.add(new NotificationWrapper<>(new ManagerNotification()); // <- contructor taking T implied for NotificationWrapper

list.add(new NotificationWrapper<>(new StaffNotification()); // <- fails because StaffNotfication != ManagerNotification

List<NotificationWrapper<?>> castList = (List<NotificationWrapper<?>>) list; // <- unsafe widening of NotificationWrapper

castList.add(new NotificationWrapper<>(new StaffNotification()); // <- compiles but throws ClassCastException at runtime

As you can see casting generic types in any way like this is not safe or desirable. To get this List more flexible you need to use wildcards with the desired bounds ("? extends Foo" or "? super Foo" or a combination of those). I recomend nipafx generics playlist to get a deeper understanding in generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM