Reputation: 23
I cant undestand why line for (Integer integer : genericClass.getList()) {
have compile error "Incompatible types: requried Object, found Integer
return value for getList is concrete and not depends of T
If I change for (GenericClass genericClass : list) {
to for (GenericClass<String> genericClass : list) {
error has gone
Why?
public class Test {
public static void main(String[] args) {
List<GenericClass<String>> list = new ArrayList<>();
for (GenericClass genericClass : list) {
for (Integer integer : genericClass.getList()) {
System.out.println(integer);
}
}
}
private class GenericClass<T extends String> {
private List<Integer> list = new ArrayList<>();
private List<Integer> getList() {
return list;
}
}
}
Upvotes: 2
Views: 61
Reputation: 1
This line for (GenericClass genericClass : list) {
gives error because you've declared GenericClass as private class GenericClass<T extends String>
.
So, whenever you've to create the object of this class you've to declare it as;
GenericClass<String> genericClass
. You've to provide the type.
Upvotes: 0
Reputation: 540
In your first for loop you didn't mentioned type. Try this
for (GenericClass<String> genericClass : list) {
for (Integer integer : genericClass.getList()) {
System.out.println(integer);
}
}
Upvotes: 0
Reputation: 1486
Your
private List<Integer> getList() {
return list;
}
Is private, but you are trying to call it anyway, did you override the default if there is any. Else set it to protected or public.
Upvotes: 0
Reputation: 15423
It works because earlier GenericClass genericClass
is equivalent to GenericClass<Object>
and Object doesn't extend String which is final.
Upvotes: 1