Reputation: 6316
I am wanting to create a new student and instantiate them with a list of subjects that they are signed up for, but am unaware if it is possible or how to accomplish it?
I have initially put an ArrayList in the constructor, but I am certain that this is wrong.
The eventual outcome is that I have a student with Name, ID and an editable list of subjects that they are studying so that they can be added to and taken out of courses as and when...
Student.java
private String name;
private int id;
private static int counter;
private ArrayList<Subjects> subjects;
public Student(String name, ArrayList<Subjects> subjects) {
this.name = name;
this.subjects = subjects;
counter++;
id=counter;
}
School.java
public class School {
List<Student> students = new ArrayList<>();
public void addStudent(String name, ArrayList<Subjects> subjects) {
Student tempStudent = new Student(name,subjects);
students.add(tempStudent);
}
}
Run.java where my problems come...
public class Run {
public static void main(String[] args) {
School school = new School();
school.addStudent("ABC", Subjects.English.toString().......... );
}
}
Subjects.java
public enum Subjects {
Maths,
English,
Science
}
Upvotes: 1
Views: 333
Reputation: 9651
Here's what I would do:
private String name;
private int id;
private static int counter;
private List<Subjects> subjects;
public Student(String name, Collection<Subjects> subjects) {
this.name = name;
this.subjects = new ArrayList<>(subjects);
counter++;
id=counter;
}
// second constructor for convenience
public Student(String name, Subjects... subjects) {
this(name, Arrays.asList(subjects));
}
...
public class School {
List<Student> students = new ArrayList<>();
public void addStudent(String name, List<Subjects> subjects) {
Student tempStudent = new Student(name,subjects);
students.add(tempStudent);
}
public void addStudent(String name, Subjects... subjects) {
Student tempStudent = new Student(name,subjects);
students.add(tempStudent);
}
}
Upvotes: 1
Reputation: 37584
You are no creating an Array
nor adding an Enum
. Change your Student
class and every method associated with it to take a List
and not an ArrayList
e.g.
private List<Subjects> subjects;
Then you could use
school.addStudent("ABC", Arrays.asList(Subjects.Maths, Subjects.English));
Upvotes: 2