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:绑定必须为正”,我不明白我在这里做错了什么?我在这里查看了很多此类问题线程,但我所做的正是他们所做的
您正在添加String
s to a List
参数化取Student
s.
当然,这不会编译。
- 添加一个构造函数到你的
Student
类,采取String
论证(以及其中的相关逻辑)。
- 然后,使用以下习语:
students.add(new Student("Student 1"));
需要注意的是,泛型恰恰会导致该阶段编译失败。
如果您使用的是原始List
(Java 4 风格),你的代码会编译,但在运行时会发生各种邪恶的情况,因为你期望Student
包含在您的对象中List
,但你会得到String
代替。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)