"no suitable method found for add(java.lang.String)"in arraylist constructor?

31,778

Solution 1

You are adding Strings to a List parametrized to take Students.

Of course this is not going to compile.

  • Add a constructor to your Student class, taking a String argument (and the relevant logic within).
  • Then, use the following idiom: students.add(new Student("Student 1"));

To be noted, generics are there precisely to fail compilation at that stage.

If you had used a raw List (Java 4-style), your code would have compiled, but all sorts of evil would have happened at runtime, since you'd expect Student objects to be contained in your List, but you'd get Strings instead.

Solution 2

Can you show the code of the Student class? Like others have said, you have a Student arraylist and are sending a String instead. That is an invalid argument.

If your Student class takes a string to be initialized, you can try:

ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("Student 1"));

Solution 3

The ArrayList, private ArrayList<Student> students can accept only Student objects.You are trying to add String to it.

If you want the list to accept String, define it like this: private ArrayList<String> student

Or, if you want the list to be of Student objects, then construct Student objects from the strings (how depends on the Student object) and add the object to list.

Share:
31,778
anony
Author by

anony

Updated on July 28, 2021

Comments

  • anony
    anony over 2 years
    import java.util.ArrayList;
    import java.util.Random;
    
    public class College
    {
        // instance variables - replace the example below with your own
        private ArrayList<Student> students;
    
        public College()
        {
            // initialise instance variables
            ArrayList<Student> students = new ArrayList<Student>();
            students.add("Student 1");
            students.add("Student 2");
            students.add("Student 3");
    
        }
    }
    

    basically it highlights the .add showing the error message "java.lang.IllegalArgumentException: bound must be positive", I don't understand what I did wrong here? I looked at a lot of these kinds of problem threads here but I did exactly what they did

  • anony
    anony over 8 years
    thank you i just realize what i did wrong now, thanks very much