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);
        }
    }
}
1
  • 2
    Cast s to Student before adding it. Commented Aug 22, 2017 at 4:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Thanks! I am using Netbeans though I didn't get any warnings.
@Snar3 netbeans is a confusing IDE in my opinion, try using Eclipse. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.