3

Here's the sample code:

public static BaseListAdapter<? extends Item> getListAdapter() {
    ...
}

...

public class MyClass<T extends Item> {
    ...
    BaseListAdapter<T> adapter = (BaseListAdapter<T>) getListAdapter();
    ...
}

The compiler complains that there's an unchecked cast.

java: unchecked cast
  need: BaseListAdapter<T>
  found:    BaseListAdapter<capture#1, ? extends Item>

I want to know why this warning is produced and how to resolve it.

Lion
  • 965
  • 10
  • 21
  • 2
    Warnings are no errors. You tell the compiler that `BaseListAdapter extends Item>` is of type `BaseListAdapter` by an explicit cast. The compiler only says that he cannot verify this, so you are on your own. – Vincent van der Weele Jul 15 '13 at 10:04
  • Please refer to this link, This may help http://stackoverflow.com/questions/262367/type-safety-unchecked-cast – Debrup Majumdar Jul 15 '13 at 10:06

2 Answers2

6

You probably want

public static <T extends Item> BaseListAdapter<T> getListAdapter() {
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Will that really solve the issue? Is the `T` here guaranteed to be same as the `T` used in the class? I don't think so, if that method is in different class than `MyClass`. – Rohit Jain Jul 15 '13 at 10:12
  • Still the warning doesn't seem to disappear – sanbhat Jul 15 '13 at 10:12
  • @RohitJain: The `T` is a different one for sure. But doesn't it still work? This is the same pattern as in `Collections#emptyList` which also returns a list that can fit "any" T. – Thilo Jul 15 '13 at 10:15
  • @Thilo. Yeah, and there also if you try to perform typecast, it will give you unchecked cast warning. – Rohit Jain Jul 15 '13 at 10:16
  • ... and that would just push a potentially dangerous cast into the method. I the case of emptyList that is safe. But usually, it's not. So I agree, the types probably have to be linked somehow. We need to see more code. – Thilo Jul 15 '13 at 10:17
  • @RohitJain: I thought the whole point of emptyList (the method) was to avoid that warning? Otherwise you can use EMPTY_LIST (the field). – Thilo Jul 15 '13 at 10:18
  • @Thilo. We get unchecked warning that we cast a to a parameterized type, or a raw type. I think, `Collections.emptyList()` automatically infers the type of `T` by the left hand side. Like in case of `List`. Although I'm not exactly sure about the behaviour. – Rohit Jain Jul 15 '13 at 10:24
0

This is because while BaseListAdapter accepts any type extending from Item, you're explicitly casting a BaseListAdapter with any ol' type to BaseListAdapter with type T, which is not necessarily the same type, hence the error.

If you want to fix it, then you need to avoid the cast altogether and manage with Item instead or make BaseListAdapter handle T and not some unnamed type ? extends Item.

Neil
  • 5,762
  • 24
  • 36