1

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);
        }
    }
}
Snar3
  • 68
  • 1
  • 11

2 Answers2

2

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.

OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
0

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.

Cardinal System
  • 2,749
  • 3
  • 21
  • 42