Raw type with list <String> gives a compilation error

I have the following general class:

import java.util.ArrayList;
import java.util.List;

public class GenericRaw<T> {
    public List<String> get() {
         return new ArrayList<>();
    }
}

Consider the case of its use:

public class Usage {
    public void doSomething() {
        GenericRaw base = new GenericRaw();
        for (String x : base.get()) {   }
    }
}

Idea gives no compilation error for this code, but the Java compiler itself:

java: incompatible types required: java.lang.String found: java.lang.Object

Reproducibility on JDK 1.6.0_33, as well as on JDK 1.7.0_17.

Can someone help me with an explanation of this problem?

The results of my research. The following options can be successfully compiled:

public void doSomething() {
    GenericRaw<?> base = new GenericRaw();
    for (String x : base.get()) {   }
}

or even:

public void doSomething() {
    GenericRaw base = new GenericRaw();
    List<String> list = base.get();
    for (String x : list) {   }
}
+1
source share
1 answer

Can someone help me with an explanation of this problem?

Of course. He follows the JLS description of raw types, section 4.8 :

, (§4.6) (. 4.5) (§10.1), . .

erasure GenericRaw<T>:

public class GenericRaw {
    public List get() { ... }
}

:

(§8.4.2) , . s , , s, , s.

(§8.4.4) (§8.4.5) , .

+3

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


All Articles