Michael
Michael

Reputation: 14258

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?

Upvotes: 2

Views: 771

Answers (4)

Kostadin Mehomiyski
Kostadin Mehomiyski

Reputation: 159

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

Upvotes: 0

user1722245
user1722245

Reputation: 2183

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

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

Upvotes: 9

Ulises
Ulises

Reputation: 13429

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) {
  // …
}

Upvotes: 0

Related Questions