问题
Can somebody help me with one little problem. I want to set for example 3 lectures to 1 student, but when i try this i can't set lectures.
student.setStudentLecture(lecture);
student.setStudentLecture(lecture1);
public class Student {
private Lecture[] lecture;
public void setStudentLecture(Lecture[] lecture) {
this.lecture = lecture;
}
public Lecture[] getStudentLecture() {
return lecture;
}
}
回答1:
You are using Array of Lecture objects and overwriting the same array with two different array references. Hence, it is not working. Use the below code:
public class Student {
private Lecture[] lecture;
public void setStudentLecture(Lecture[] lecture) {
this.lecture = lecture;
}
public Lecture[] getStudentLecture() {
return lecture;
}
public static void main(String[] args) {
Student student = new Student();
Lecture[] lectures = new Lecture[3];
lectures[0] = new Lecture("Physics");
lectures[1] = new Lecture("Mathematics");
lectures[2] = new Lecture("Chemistry");
student.setStudentLecture(lectures);
Lecture[] lectures1 = student.getStudentLecture();
for (int i = 0; i <lectures1.length; ++i) {
System.out.println(lectures1[i].getName());
}
}
}
public class Lecture {
private String name;
public Lecture(String name) {
this.name = name;
}
public String getName(){
return name;
}
}
回答2:
As you setter is also array, you can create the Array of Lecture and set it to Student.
sample:-
Student student = new Student();
Lecture lecture = new Lecture();
Lecture lecture1 = new Lecture();
Lecture[] lectureArr = new Lecture[]{lecture, lecture1};
student.setStudentLecture(lectureArr);
And also you have studentLecture as array, then why you want to assign different array twice, you can combine both array and assign it.
来源:https://stackoverflow.com/questions/43718691/setter-getter-arrays-java