Setter Getter Arrays Java

帅比萌擦擦* 提交于 2020-07-07 23:29:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!