使用向量的Java警告:未经检查的调用添加(E) [英] Java Warning using Vectors: unchecked call to add(E)
问题描述
攻击代码位
Vector moves = new Vector();
moves.add(new Integer(x));
错误:
ConnectFour.java:82: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector moves.add(new Integer(x));
不确定这样的错误需要多少信息......
Not really sure how much info is needed for an error like this....
推荐答案
问题是上面的代码没有使用泛型。
The problem is that the code above is not using generics.
以下内容可行:
Vector<Integer> moves = new Vector<Integer>();
move.add(new Integer(x));
<>
(在 Vector
的情况下,要保留的元素的类型参数 E
)告诉编译器什么类型的它应该期待的对象。
The type name inside the <>
(in the case of Vector
, the type parameter E
for the element to hold) tells the compiler what type of object it should expect.
如果试图添加一个具有指定类型的对象,例如在这种情况下,尝试添加 String
to和 Vector< Integer>
,将发生编译时错误,表明某种类型的对象不是预期类型的正在添加。
If one tries to add an object that is of the specified type, such as in this case, trying to add an String
to and Vector<Integer>
, an compile-time error will occur, indicating that a type of object that is not of the expected type is being added.
这就是说,应该尽量不要使用 Vector
类。出于更多目的,实现 的类列表
,例如 <$ href =http://java.sun.com/docs/books/tutorial/collections/index.html = ArrayList
noreferrer> Java Collections Framework 就足够了,表现更好。
That said, one should try not to use the Vector
class. For more purposes, a class implementing List
such as ArrayList
from the Java Collections Framework would be sufficient, and better performing.
编辑
虽然与泛型问题没有直接关系,但Adam Paynter在关于使用自动装箱的评论中提出了一个很好的观点。
Although not directly related to the question about generics, Adam Paynter brought up a good point in the comments about the use of auto-boxing.
从Java 5开始,原语及其包装类,例如 int
和 Integer
将根据需要自动相互转换。
Since Java 5, primitives and their wrapper classes, e.g. int
and Integer
will be automatically converted between each other as necessary.
因此,可以将指定为 int
或 int
字面值的值添加到类中期待整数
:
Therefore, it is possible to add an value specified as an int
or an int
literal into a class expecting an Integer
:
Vector<Integer> v = new Vector<Integer>();
v.add(5); // Not necessary to use an Integer value.
这篇关于使用向量的Java警告:未经检查的调用添加(E)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!