Why do collections that are not related to the template class drop their type? Here is an example: (Sorry, it will not compile because of the error I'm confused about.)
package test;
import java.util.ArrayList;
import java.util.List;
public class TemplateTest {
public static class A { }
public static class B<T extends Comparable> {
List<A> aList = new ArrayList<A>();
public List<A> getAList() {
return aList;
}
public int compare(T t, T t1) {
return t.compareTo(t1);
}
}
public static void main(String[] args) {
B b = new B();
for (A a : b.getAList()) { //THIS DOES NOT WORK
}
List<A> aList = b.getAList(); //THIS WORKS
for (A a : aList) {
}
}
}
This code throws an error upon compilation:
test/TemplateTest.java:24: incompatible types
found : java.lang.Object
required: test.TemplateTest.A
for (A a : b.getAList()) {
If I specify the template of B
like B<String>
, or if I remove the template from B completely, then everything is ok.
What's going on?
EDIT: people pointed out there was no need to make B generic so I added to B