Java List parameterized?

nacho4d picture nacho4d · Aug 31, 2009 · Viewed 9.3k times · Source

I am quite new to Java ... I wrote a class called DLPFile which is basically a container of other objects like Strings, ints, floats, etc.

When putting my files into a List and then saving it in my session (which is from Map class) variable is easy;

DLPFile file = new DLPFile();
List <DLPFile >fileList =  new ArrayList <DLPFile>();
fileList.add(file);
session.put("filesList", fileList);

but how do I retrieve the list from the session var? When I do:

List <DLPFile files = (List) session.get("fileslist");

I got some warnings:

"List is a raw type.References to generic type List<E> should be parameterized."

I tried

List <DLPFile files = (List <DLPFile> ) session.get("fileslist");   
List <DLPFile files = (List ) session.get("fileslist")<DLPFile>; and
List <DLPFile files = (List) <DLPFile>  session.get("fileslist");

but none works

I suppose this is kind of a "casting" problem... (maybe?)

Thanks in advance ;)

Answer

Daff picture Daff · Aug 31, 2009

This is because of the Generics Type erasure. The compiler has no way to determine the actual generic type argument when you get it from your session (except if you session.get takes a Class<T> argument to cast it accordingly), because the session probably only returns the type of object. You can make sure that your object is an instance of List, but the generic type information is lost (basically the compiler converts it to a List<Object> internally). That is why you get the warning, because only you as the programmer can know if the generic type parameter you want to cast it to is the right one.

If you don't like the warning you may add an

@SuppressWarnings("unchecked")

Annotation at the beginning of your method.