Odd case in Java generics - should class level generic affect getters? -
this question has answer here:
i came across weird case while writing unit test today (simplified below).
import java.util.collection; import java.util.collections; public class test { public static class testclass<t> { private final collection<string> field = collections.emptylist(); public collection<string> getfield(){ return this.field; } } public static void main(string[] args){ // unchecked assignment, why? testclass case1 = new testclass(); collection<string> field1 = case1.getfield(); // ok testclass case2 = new testclass(); collection field2 = case2.getfield(); // adding type parameter class makes unchecked assignment dissapear testclass<string> case3 = new testclass<>(); collection<string> field3 = case3.getfield(); } }
running javac test.java -xlint:unchecked
(or pasting ide) yields following message:
test.java:17: warning: [unchecked] unchecked conversion collection<string> field1 = case1.getfield(); ^ required: collection<string> found: collection 1 warning
it looks removing generic type parameter class variable declaration leaves compiler unable infer type of getfield()
, though declared returning collection<string>
. bug? if not, can explain why happening? totally thrown loop while debugging hamcrest matcher. last thing expected causing problem.