Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 727
anony Avatar asked May 12 '26 18:05

anony


2 Answers

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.

like image 184
Mena Avatar answered May 14 '26 07:05

Mena


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"));
like image 36
John-Paul Ensign Avatar answered May 14 '26 06:05

John-Paul Ensign