【问题标题】:Java arrayList incompatible with VectorJava arrayList 与 Vector 不兼容
【发布时间】:2017-07-13 17:21:52
【问题描述】:
我的代码如下
private Vector<Vector<Object>> barCode;
private boolean isBarCode(String temp) {
for (Vector<Object> link : barCode) {
if (link.get(0).toString().equals(temp)) {
return true;
}
}
return false;
}
我遇到了错误。
Caused by: java.lang.ClassCastException: java.util.ArrayList incompatible with java.util.Vector
在for循环行。
请问有什么意见吗?
【问题讨论】:
标签:
java
arraylist
vector
collections
【解决方案1】:
private List<List<Object>> barCode;
private boolean isBarCode(String temp) {
for (List<Object> link : barCode) {
if (link.get(0).toString().equals(temp)) {
return true;
}
}
return false;
}
Use the interface, not the implementation。 Vector 和 ArrayList 都实现了 List 接口,因此这允许任何一个(以及任何其他实现)的实例。我还建议在您的其余代码中标准化创建 ArrayList 实例,除非您确定需要 other implementations 的功能。
【解决方案2】:
您的barCode 包含ArrayList 而不是Vector。
有人放错了容器。您的示例中没有足够的数据来找出位置和原因。
您可以将for (Vector<Object> link : barCode) 替换为for (ArrayList<Object> link : barCode) 并将Vector<Vector<Object>> barCode 替换为Vector<ArrayList<Object>> barCode,但我强烈建议您在找出barCode 包含ArayList 的原因之前不要这样做 .
这是因为在您的代码中某处使用了原始泛型(Vector 没有泛型参数)。