java - Java 中的 Setter Getter 数组

标签 java arrays setter getter

有人可以帮我解决一个小问题吗?例如,我想为 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;
    }
}

最佳答案

您正在使用 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;
    }
}

关于java - Java 中的 Setter Getter 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43718691/

相关文章:

objective-c - setNeedsLayout 如何工作?

c# - 为什么我的属性(property)不做检查?

java - Kotlin 数据类 equals() 方法是否可以在不进一步修改的情况下与 JPA 一起使用?

java - 输入套接字意外关闭时吞下 IOException

c# - BitConverter 的 C++ 等价物

javascript - 如何从 Javascript 对象中删除所有 getter 和 setter 并保持纯值

java - Python 3.7 连接到 MAC 上的 HSQLDB

从头开始创建缓存时的 Java 和线程安全

javascript - 如何通过对象的唯一属性值从数组中获取对象?

php - 随机播放函数不随机播放数组元素 (PHP)