类型安全:方法..属于原始类型。参考泛型应参数化 [英] Type safety: The method.. belongs to the raw type.. refs to generics should be parameterized

查看:137
本文介绍了类型安全:方法..属于原始类型。参考泛型应参数化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Eclipse给了我一个警告(在标题中),在一个工作项目中只使用以下代码,但没有任何东西,但是一个虚拟类和一个主要方法:

Eclipse gives me the warning (in the title) using just the following code in a working project with nothing in it but a dummy class and a main method:

List a = new ArrayList();
List<Integer> b = new ArrayList<Integer>();
int x = 19;
a.add(x);

最后一行触发警告。我不知道我在这里做错什么,还是真的,我甚至在做什么。我是Java学生,遵循可疑的教程,我正在尝试了解泛型。假设变量x没有说明类型的安全性。我尝试将其转换为对象类型(我认为没有,因为它已经是),它没有工作。

The last line triggers the warning. I'm not sure what I am doing wrong here, or really, what I am even doing. I am a Java student following a dubious tutorial and I am attempting to understand generics. Supposedly, variable x doesn't illustrate type safety. I tried casting it to the Object type (which I think does nothing because it already is) and it didn't work.

我如何解决这个警告? p>

How might I resolve this warning?

推荐答案

您已声明列出没有type参数的。这就是为什么eclipse正在抱怨类型安全性,因为你可以添加任何类型的对象到该列表。

You have declared List a without the type parameter. This is why eclipse is complaining about type safety, as you could add objects of any type to that list.

如果你看看 ArrayList api ,看看类声明,你看到它被声明为这个:

If you look at the ArrayList api and take a look at the class declaration, you see it is declared like this:

public class ArrayList<E>

用任何你想要的课程代替E。

Substitute E with any class you wish.

With List< Integer> b 你已经明确告诉编译器,列表是仅保存 Integer 对象的实例,编译器可以验证这一点,从而给出类型安全。

With List<Integer> b you have explicitly told the compiler that the list is to hold instances of Integer objects only, and the compiler can verify this, thus giving you type safety.

这篇关于类型安全:方法..属于原始类型。参考泛型应参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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