我试图理解inhertitance和ArrayList是如何工作的,所以我有以下代码 它有一个类,它是保存数据的数据库
public class Database {
ArrayList<Student> students;
ArrayList<Course> courses;
public boolean doesIDExist(ArrayList<RegistrationSystem> array, int id){
boolean exist = false;
for (RegistrationSystem array1 : array) {
if (array1.getId() == id) {
exist = true;
break;
}
}
return exist;
}
public boolean addStudent(int id, String name, String surname){
if( doesIDExist(students, id)){
return false;
}
students.add(new Student(id, name, surname));
return true;
}
}
学生和课程都是注册系统的子类
public class RegistrationSystem {
protected int id;
public int getId() {
return id;
}
}
但我在这一行中收到错误:
if( doesIDExist(students, id))
incompatible types: ArrayList< Student > cannot be converted to ArrayList< RegistrationSystem >
我不太明白为什么会收到这个错误!
答案 0 :(得分:5)
您的方法需要RegistrationSystem
的列表而不是Student
的列表。
您必须更改为:
public boolean doesIDExist(ArrayList<? extends RegistrationSystem> array, int id){
答案 1 :(得分:1)
在这里 <welcome-file>index.jsp</welcome-file>
,您正在传递if( doesIDExist(students, id)
个对象而不是Student
个对象。作为更好的选择,您必须实施一种新方法来识别现有的学生ID
答案 2 :(得分:1)
虽然Student
是RegistrationSystem
的子类型,但{em>不 ArrayList<Student>
是ArrayList<RegistrationSystem>
的子类型。
原因是,这可能导致非类型安全的代码。请考虑以下代码:
void method1(ArrayList<RegistrationSystem> listOfRegistrationSystems) {
listOfRegistrationSystems.add(new Course());
}
void method2() {
ArrayList<Student> listOfStudents = new ArrayList<>();
method1(listOfStudents);
Student student = listOfStudents.get(0);
// Ooops! The first element of listOfStudents is not a Student!
}
为了解决这个问题,Java提供了有界类型变量和有界通配符。您可以使用ArrayList<? extends RegistrationSystem>
,这意味着:ArrayList
某个未知子类RegistrationSystem
的实例ArrayList<? extends RegistrationSystem>
。在您的情况下,ArrayList<RegistrationSystem>
可以是ArrayList<Student>
,ArrayList<Course>
或public boolean doesIDExist(ArrayList<? extends RegistrationSystem> array, int id){
boolean exist = false;
for (RegistrationSystem array1 : array) {
if (array1.getId() == id) {
exist = true;
break;
}
}
return exist;
}
中的一个。所以你必须改变你的方法
alpha
答案 3 :(得分:0)
你在这里尝试做的是这样的:
ArrayList<RegistrationSystem> array = students;
Java不允许这个
更改您的方法签名,而不是doesIDExist(ArrayList<? extends RegistrationSystem>,int id)
答案 4 :(得分:0)
当方法仅接受RegistrationSystem时,您正在尝试传递Student对象的ArrayList。