0

I came across this weird case while writing a 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, but why?
        TestClass case1 = new TestClass();
        Collection<String> field1 = case1.getField();

        // This is ok
        TestClass case2 = new TestClass();
        Collection field2 = case2.getField();

        // Adding a type parameter to the class makes the unchecked assignment dissapear
        TestClass<String> case3 = new TestClass<>();
        Collection<String> field3 = case3.getField();
    }
}

Running javac Test.java -Xlint:unchecked (or pasting into an IDE) yields the following message:

Test.java:17: warning: [unchecked] unchecked conversion
        Collection<String> field1 = case1.getField();
                                                  ^
  required: Collection<String>
  found:    Collection
1 warning

It looks like removing the generic type parameter from the class variable declaration leaves the compiler unable to infer the type of the getField(), even though it is declared as returning a Collection<String>. Is this a bug? If not, can someone explain why something like this is happening? I was totally thrown for a loop while debugging a Hamcrest matcher. This was the last thing I expected to be causing my problem.

Anthony Naddeo
  • 2,497
  • 25
  • 28
  • 1
    *Is this a bug? If not, can someone explain why something like this is happening?* No. It's a [raw type](http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html). Don't use raw types. – Elliott Frisch Jun 02 '16 at 00:23
  • 3
    Raw types will poison anything they come into contact with, even when seemingly unrelated. See [here](http://stackoverflow.com/questions/1040540/why-are-generics-completely-disabled-when-you-ignore-a-parameter-type) for a similar example. – shmosel Jun 02 '16 at 00:25
  • Well, that's definitely what's going on here. Thanks for pointing that out. What is the convention for accepting answers when they come in the form of comments? – Anthony Naddeo Jun 02 '16 at 00:38
  • Upvote the answers (and/or the question itself) on the duplicate question if you like them. Nothing else to do. – Tom Jun 02 '16 at 00:40

0 Answers0