使用 vector 的 Java 警告 : unchecked call to add(E)

标签 java vector

有问题的代码

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

不太确定这样的错误需要多少信息......

最佳答案

问题是上面的代码没有使用generics .

以下将起作用:

Vector<Integer> moves = new Vector<Integer>();

move.add(new Integer(x));

<> 中的类型名称(在 Vector 的情况下,要保存的元素的类型参数 E)告诉编译器它应该期望什么类型的对象。

如果尝试添加指定类型的对象,例如在本例中,尝试添加 StringVector<Integer> ,会发生编译时错误,表明正在添加的对象类型不是预期的类型。

也就是说,应该尽量不要使用 Vector 类(class)。出于更多目的,实现 List 的类如 ArrayList 来自 Java Collections Framework就足够了,而且性能更好。

编辑

虽然与泛型问题没有直接关系,但 Adam Paynter 在关于使用自动装箱的评论中提出了一个很好的观点。

从 Java 5 开始,原语及其包装类,例如intInteger将根据需要在彼此之间自动转换。

因此,可以添加一个指定为 int 的值或 int将文字放入期望 Integer 的类中:

Vector<Integer> v = new Vector<Integer>();
v.add(5);    // Not necessary to use an Integer value.

关于使用 vector 的 Java 警告 : unchecked call to add(E),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1840590/

相关文章:

java - 在 Android 中通过 Intent 使用 Zxing 扫描条码时如何更改文本?

java.lang.ClassCastException : [Ljava. lang.Object;无法转换为 com.xl.entity.Users

java - 编程练习如下 : exercise on for-structure. 如何编写一个程序,在圣诞树下面打印?

c++ - 引用绑定(bind)到类型为 'value_type' 的空指针

c++ - 为什么 std::vector::operator[] 比 std::vector::at() 快 5 到 10 倍?

c++ - 特定特化的通用容器的功能

javascript - 无法在android webview中实现javascript

java - Java注解中的调用方法

graphics - 如何与雅典建立线路?

vector - clojure:从 xml 创建 map 向量