问题
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
回答1:
You are adding String
s to a List
parametrized to take Student
s.
Of course this is not going to compile.
- Add a constructor to your
Student
class, taking aString
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 String
s instead.
回答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"));
回答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.
来源:https://stackoverflow.com/questions/34137792/no-suitable-method-found-for-addjava-lang-stringin-arraylist-constructor