“在arraylist构造函数中找不到合适的add(java.lang.string)方法”?

kyvafyod  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(679)
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");

        }
    }

基本上它突出显示了.add显示错误消息“java.lang.illegalargumentexception:bound must be positive”,我不明白我在这里做错了什么?我在这里查看了很多这样的问题线程,但我做的正是它们所做的

jljoyd4f

jljoyd4f1#

你能出示学生班级的代码吗?正如其他人所说,您有一个student arraylist,并发送一个字符串。那是一个无效的论点。
如果您的学生类需要初始化字符串,您可以尝试:

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

uqxowvwt2#

数组列表, private ArrayList<Student> students 只能接受 Student 对象。您正在尝试添加 String 去吧。
如果希望列表接受字符串,请按以下方式定义: private ArrayList<String> student 或者,如果你想让名单 Student 对象,然后构造 Student 字符串中的对象(如何取决于 Student 对象)并将对象添加到列表中。

eaf3rand

eaf3rand3#

您正在添加 String s到a List 参数化为 Student s。
当然,这不会被编译。
将构造函数添加到 Student 同学们,请 String 论证(以及其中的相关逻辑)。
然后,使用以下习语: students.add(new Student("Student 1")); 需要注意的是,泛型正是在那个阶段编译失败的原因。
如果你用的是生的 List (java4风格),您的代码本来可以编译,但运行时会发生各种各样的错误,因为您会预料到 Student 要包含在 List ,但你会得到 String 取而代之的是。

相关问题