本文介绍了错误:类型不兼容的对象无法转换[ArrayList]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的for循环声明中出现编译器错误:incompatible types: Object cannot be converted to Type2
I am getting a compiler error in my for loop declaration: incompatible types: Object cannot be converted to Type2
我正在尝试这样做:
这是代码:
import java.util.ArrayList;
public class Test2 {
String name;
int value;
public ArrayList list = new ArrayList<Test2>();
public void q() {
for(Test2 w : list) { // Here is the error: 'incompatible types: Object cannot be converted to Test2'
if(w.value == 10)
System.out.println(w.name);
}
}
}
推荐答案
Java无法知道列表中是否存在类型为Test2
的对象.您需要对其进行参数化.可以将list
显式声明为public ArrayList<Test2> list = new ArrayList<Test2>();
,也可以将其强制转换为(Test2 w : (ArrayList<Test2>)list)
.
Java has no way of knowing to expect an object of type Test2
in the list; you need to parameterize it. Either explicitly declare list
as public ArrayList<Test2> list = new ArrayList<Test2>();
, or cast it in the loop: (Test2 w : (ArrayList<Test2>)list)
.
这篇关于错误:类型不兼容的对象无法转换[ArrayList]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!