I am getting a compiler error in my for loop declaration: incompatible types: Object cannot be converted to Type2
I am trying to do this : Java - List of objects. Find object(s) with a certain value in a field
Here is the code:
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 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With