Java Generics - Endangered Type Information?

OK. I know that Java generics can be a minefield for reckless ones, but I just came across unintuitive (for me, all the same) behavior that I was wondering about if anyone could explain: firstly, here is a class that consists of:

public class Dummy { public List<? extends Number> getList() { return new ArrayList<Number>(); } public static void main(String[] args) { Dummy dummy = new Dummy(); for (Number n: dummy.getList()) { System.out.println(n); } } } 

Simple things. Now I make one change by adding a parameter of type T to Dummy:

 public class Dummy<T> { 

Now the class does not compile, indicating the error "Type mismatch: cannot be converted from the type of the Object element to Number" into the for () statement

It seems that since I parameterize the Dummy class, creating a new Dummy () in the main method (without specifying a type parameter) makes the type information for the getList () method no longer available: The compiler no longer knows the type of list items, so they cannot be assigned to a loop variable of type Number. Why is this type of information missing, given that the <T> declaration in the class has nothing to do with <? extends the number> declaration in the getList () method?

Also, if now I am modifying my Dummy instance as follows:

 Dummy<?> dummy = new Dummy(); 

Then the type information becomes available again, and the class compiles again. So, why does the “Dummy of unknown type” allow you to store getList () type information, while the Dummy (supposedly unknown type, since I did not specify the parameter) loses it?

Maybe I'm Dummy :-)

+2
source share
2 answers

The general idea is that all type-related information is deleted if you are using an unprocessed version of a parameterized type. This includes type information implied by class type parameters or general method parameters.

A very similar example is described here .

+4
source

I came across this before, but I’ll explain that this can cause additional confusion, so I’ll link you to the JLS section on “Raw Types ”, which you can read to fully understand what is happening, then you can come back with additional questions if not get it.

0
source

Source: https://habr.com/ru/post/1391341/


All Articles