'Is there a way to add a specific instance of a class1 to class2 if class1 is initialized as an array of classes?

While this program works, the setIndex method in student adds all instances of the class array of subject. is there a way to make this program be more flexible in the amount of classes added?

Is there is a better way to initialize classes without them being an array of classes and have this program work?

main:

public class Main {

    public static void main(String[] args) {
        Predmet [] predmet = new Predmet [3];
        predmet [0] = new Predmet(1,"Algebra",true,7);
        predmet [1] = new Predmet(2,"Analiza",false,5);
        predmet [2] = new Predmet(3, "TOR",true,8);

        Student student1 = new Student(1,"Nikola","P");
        student1.setIndex(predmet);
        student1.printcompleted();
    }
}

subject:

public class Predmet {

    private int id;
    private String ime;
    private boolean opravil;
    private int ocena;

    public Predmet(int id, String ime, boolean opravil, int ocena) {
        this.id = id;
        this.ime = ime;
        this.opravil = opravil;
        this.ocena = ocena;
    }

    public int getId() {
        return id;
    }

    public String getIme() {
        return ime;
    }

    public boolean isOpravil() {
        return opravil;
    }

    public int getOcena() {
        return ocena;
    }
}

student:

public class Student {

    private int vpisna_stevilka;
    private String ime;
    private String priimek;
    private Predmet[] index;

    public Student(int vpisna_stevilka, String ime, String priimek) {
        this.vpisna_stevilka = vpisna_stevilka;
        this.ime = ime;
        this.priimek = priimek;
    }

    public void setIndex(Predmet[] index) {
        this.index = index;
    }

    public void printcompleted() {
        for (int i = 0; i < index.length; i++) {
            if (index[i].isOpravil()) {
                System.out.println(index[i].getIme());
            }
        }
    }

}

Any help would be very much appreciated, thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source