简体   繁体   中英

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?

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);

You are casting it to the parent A , if you want to avoid that then change your return type for myMethod :

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

if you define:

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

then you can call:

List = MyClass.myMethod(List a){}

it is generic method, is`nt it?

Jirka

This is how you can avoid the cast with static methods:

public class MyClass {
    public static List<? extends A> myMethod(List<? extends A> a) {
        return a;
    }

    public static void main(String[] args) {
        List newList = new ArrayList<A>();
        List<?> newList2 = new ArrayList<A>();
        List<B> oldList = new ArrayList<B>();

        newList = MyClass.myMethod(oldList);
        newList2 = MyClass.myMethod(oldList);
    }
}

In the code above, B extends A. When newList variable is defined as List without generics or as List with wildcard type (List< ? >) cast is not necessary. On the other hand if you only want to get rid the warning you can use ' @SuppressWarning ' annotation. Check this link for more info What is SuppressWarnings ("unchecked") in Java?

Here is simple example for @SuppressWarnings ("unchecked") :

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

@SuppressWarnings ("unchecked")
newAList = (List<A>) MyClass.myMethod(oldAList);

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