1

I have the following generic Java class:

class A<T> {
    List<A> list;

    List<A> getList() {
        return list;
    }
}

When I try to get the first element of the list

A a = new A();
A b = a.getList().get(0);

I have the compiler error:

Type mismatch: cannot convert from Object to A

If I introduce an intermediary list:

A a = new A();
List<A> sameList = a.getList();
A b = sameList.get(0);

the error disappears, but the warning appears:

Type safety: The expression of type List needs unchecked conversion to conform to List<A>

The variable sameList has the same type as the method getList(). I am ready to put up with it, but I want to understand the reason. Why is there is a conversion?

tashuhka
  • 5,028
  • 4
  • 45
  • 64
user3803250
  • 13
  • 1
  • 1
  • 3

1 Answers1

4

This is one of the fun parts about raw types. Not only do you not get generic checks on the raw type itself, but it also causes generic checks for all interacting code to be skipped too.

Thus, when you use the raw type A, the List<A> you defined inside A is actually erased to List, so that getList returns a raw type List, and get(0) would return an Object.

This is also why you get an "unchecked conversion" warning. getList() returns a List, not a List<A>. So assigning a raw type List to a List<A> will produce an unchecked conversion warning.

The variable sameList has the same type as the method getList()

So you're actually wrong, here. sameList has a different type as the return type of getList() for the raw type A.

To solve this you'll need to parameterize all uses of A in your code.

awksp
  • 11,764
  • 4
  • 37
  • 44