Reputation: 68
I'm getting the error
no suitable method found for add(Object), method Collected.add(Student is not applicable)
when I try the following code. I swear I've done it this way before? So confused. Appreciate any insights. Cheers
//Sort and display list of Student objects by sortBy (surname or id)
public static void sortAndDisplayStudents(String sortBy, ArrayList<Object> objList) {
ArrayList<Student> students = new ArrayList<>();
//Add all Objcets in objList that are a Student
for(Object s: objList) {
if(s instanceof Student) {
students.add(s);
}
}
}
Upvotes: 1
Views: 53
Reputation: 3422
Just to avoid any errors, change the way you construct the array list:
ArrayList<Student> students = new ArrayList<>();
ArrayList<Student> students = new ArrayList<Student>();
As for the add method, you want to cast to the passing object otherwise the JVM will not know that the object being passed is instanceof
Student:
students.add((Student) s);
Also, you should get an IDE, they usually solve these problems before they happen.
Upvotes: 0
Reputation: 5993
ArrayList<Student> students = new ArrayList<>();
shows that students
is a ArrayList
that contain the Object Student
.
Therefore you need to cast your s
Object to Student
before adding it to the students
list. like such students.add((Student)s);
Here is how you cast Object in Java.
Upvotes: 2