[英]Setter Getter Arrays Java
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.
例如,我想为1个学生设置3个讲座,但是当我尝试该课程时,我无法设置讲座。
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;
}
}
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;
}
}
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. 另外,您还有studentLecture作为数组,那么为什么要两次分配不同的数组,您可以组合两个数组并进行分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.