Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: incompatible types Object Could not be converted [ArrayList] [duplicate]

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);
        }
    }
}
like image 986
Chard Avatar asked Jun 15 '26 10:06

Chard


1 Answers

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).

like image 108
TayTay Avatar answered Jun 17 '26 00:06

TayTay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!