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

三世轮回 提交于 2021-02-05 06:36:05

问题


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 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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!