错误:不兼容的类型对象无法转换[ArrayList]

时间:2015-10-29 18:21:15

标签: java for-loop arraylist error-handling syntax-error

我在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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Java无法知道在列表中期望类型为Test2的对象;你需要参数化它。要么list明确声明为public ArrayList<Test2> list = new ArrayList<Test2>();,要么将其投放到循环中:(Test2 w : (ArrayList<Test2>)list)