Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and static methods

I have this static method

public static List<? extends A> myMethod(List<? extends A> a) {
  // …
}

which I'm calling using

List<A> oldAList;
List<A> newAList = (List<A>) MyClass.myMethod(oldAList);

This gives a warning because of the unchecked cast to List<A>. Is there any way of avoiding the cast?

like image 975
Michael Avatar asked Mar 31 '26 14:03

Michael


1 Answers

You need to define the type returned matches the argument (and extends A)

public static <T extends A> List<T> myMethod(List<T> a) {
    // …
}

Then you can write

List<E> list1 = .... some list ....
List<E> list2 = myMethod(list1); // assuming you have an import static or it's in the same class.

or

List<E> list2 = SomeClass.myMethod(list1);
like image 186
Peter Lawrey Avatar answered Apr 03 '26 05:04

Peter Lawrey



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!