The compiler doesn't infer the type, because you're instantiating a raw ArrayList
. But it's smart enough to warn you that there might be problems when working with this (raw) object.
It's worth mentioning the reason behind this warning. Due to the type erasure, the parametric information (
) about the List
will be completely gone at Runtime, when the variable would hold elements of type Object
. Consider this snippet:
List rawList = new ArrayList(); //raw list
rawList.add(new String("hello"));
rawList.add(new Double(12.3d));
List intList = rawList; // warning!
This snippet will compile, but will generate few warnings. Having a raw list (rawList
), you can add any non-primitive type to the list, including String
, Double
, etc. But when assigning this collection to a list, which is specified to hold only integers, then this is a problem. At Runtime you'll get a ClassCastException
when trying to fetch some element from the intList
, which is supposed to be an Integer
, but in reality is a String
or something else.
Long story short - do not mix raw types with Generics!
In your case, the compiler would possibly have inferred the type, if you have used the diamond:
List list = new ArrayList<>(); //¯\_(ツ)_/¯
↑↑