Home > OS >  Casting list of one type with generic to another
Casting list of one type with generic to another

Time:06-22

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.

CodePudding user response:

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.

  • Related