"在arraylist构造函数中没有为add(java.lang.String)找到合适的方法吗?

ano*_*ony 2 java random constructor arraylist

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");

        }
    }
Run Code Online (Sandbox Code Playgroud)

基本上它突出显示.add显示错误消息"java.lang.IllegalArgumentException:bound必须为正",我不明白我在这里做错了什么?我在这里查看了很多这类问题,但我确实做了他们所做的

Men*_*ena 9

您正在将Strings 添加到List参数化以获取Students.

当然这不会编译.

  • 在你的Student类中添加一个构造函数,接受一个String参数(以及其中的相关逻辑).
  • 然后,使用以下习语: students.add(new Student("Student 1"));

需要注意的是,泛型正是因为那个阶段的编译失败了.

如果您使用了原始List(Java 4风格),您的代码将被编译,但是在运行时会发生各种各样的恶意,因为您希望Student对象包含在您的代码中List,但您会得到它String.