我在for循环声明中遇到编译器错误:incompatible types: Object cannot be converted to Type2
我正在尝试这样做:Java - List of objects. Find object(s) with a certain value in a field
以下是代码:
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);
}
}
}
答案 0 :(得分:1)
Java无法知道在列表中期望类型为Test2
的对象;你需要参数化它。要么list
明确声明为public ArrayList<Test2> list = new ArrayList<Test2>();
,要么将其投放到循环中:(Test2 w : (ArrayList<Test2>)list)
。