“在数组列表构造函数中没有找到适合 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");
}
}
基本上它突出显示了错误消息java.lang.IllegalArgumentException:bound must be positive"的.add,我不明白我在这里做错了什么?我在这里查看了很多此类问题线程,但我完全按照他们的要求做了
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
s 添加到参数化的 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.
这篇关于“在数组列表构造函数中没有找到适合 add(java.lang.String)"的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!