“在arraylist构造函数中找不到适用于add(java.lang.String)的合适方法"? [英] "no suitable method found for add(java.lang.String)"in arraylist constructor?
问题描述
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:绑定必须为正",我不明白我在这里做错了什么吗?我在这里查看了许多这类问题线程,但我确实做了他们所做的事情
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
推荐答案
您正在将 String
添加到参数化的 List
中以接受 Student
s.
You are adding String
s to a List
parametrized to take Student
s.
这当然不会编译.
- 在您的
Student
类中添加一个构造函数,并接受一个String
参数(以及其中的相关逻辑). - 然后,使用以下成语:
students.add(new Student("Student 1"));
- 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.
如果您使用了原始的 List
(Java 4样式),则您的代码将已经编译,但是由于您希望 Student,在运行时会发生种种弊端
对象包含在您的 List
中,但是您将得到 String
s.
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.
这篇关于“在arraylist构造函数中找不到适用于add(java.lang.String)的合适方法"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!