2

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?

Michael
  • 13,838
  • 18
  • 52
  • 81
  • What is oldAList defined as? newAList? The point of generics is to avoid casting, but you'll need to provide a bit more detail. – Mikezx6r Dec 17 '12 at 16:01

4 Answers4

9

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);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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) {
  // …
}
Ulises
  • 13,229
  • 5
  • 34
  • 50
0

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

user1722245
  • 2,065
  • 1
  • 18
  • 31
0

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);
Community
  • 1
  • 1