Setter Getter 数组 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43718691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setter Getter Arrays Java
提问by Spongi
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;
}
}
回答by Avi C
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:
您正在使用 Array of Lecture 对象并用两个不同的数组引用覆盖同一个数组。因此,它不起作用。使用以下代码:
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;
}
}
回答by Sandeepjn
As you setter is also array, you can create the Array of Lecture and set it to Student.
由于您的 setter 也是数组,因此您可以创建讲座数组并将其设置为学生。
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作为数组,那么为什么你要分配不同的数组两次,你可以组合两个数组并分配它。