Java List参数化? [英] Java List parameterized?

查看:448
本文介绍了Java List参数化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java很新颖...
我写了一个名为DLPFile
的类,它基本上是一个包含字符串,整数,浮点数等其他对象的容器。 b

将我的文件放入一个List中,然后将它保存在我的会话中(来自Map类)变量很简单;

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

但是如何从会话var检索列表?
当我这样做时:

 列出< DLPFile档案=(List)session.get(fileslist); 

我收到了一些警告:

 List是一个原始类型。对泛型类型List< E>的引用应该被参数化。 

我试过

  List< DLPFile files =(List< DLPFile>)session.get(fileslist); 
List< DLPFile files =(List)session.get(fileslist)< DLPFile>;和
列出< DLPFile文件=(列表)< DLPFile> session.get( fileslist);

但没有任何作用



我想这个是一种铸造的问题......(也许?)

预先致谢)

解决方案

这是因为泛型类型擦除。当你从会话中获得它时,编译器无法确定实际泛型类型参数(除非session.get接受Class< T>参数来相应地转换它),因为会话可能只返回对象的类型。您可以确保您的对象是List的一个实例,但是泛型类型信息会丢失(基本上,编译器会在内部将它转换为List< Object>)。这就是为什么你得到警告的原因,因为只有你作为程序员才能知道你想要转换的泛型类型参数是否合适。



如果你不喜欢不喜欢可能添加的警告

  @SuppressWarnings(unchecked)



您的方法开始处的注释。


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 ;)

解决方案

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.

这篇关于Java List参数化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆