2017-10-09 61 views
1

我想創建一個新的學生,並與它們簽署了科目列表實例化它們,但我不知道是否有可能或如何完成它?採取設置在構造枚舉和創建列表 - Java的

我已經初步建成一個ArrayList構造函數,但我可以肯定,這是錯誤的。

最終的結果是,我有一個名稱,ID和他們正在研究,使他們可以添加到和取出的課程,並且當受試者可編輯列表中的學生...

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在我的問題來了...

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 
} 
+1

試試這個'school.addStudent( 「ABC」 ,Arrays.asList(Subjects.English));' – xxlali

+1

@xxlali是的,但是論據sho被聲明爲'List ',而不是'ArrayList '。 –

+0

@MauricePerry是的,你是對的。 – xxlali

回答

2

你沒有創建一個Array也不添加Enum。更改Student類以及與其相關聯的每一個方法採取List而不是ArrayList例如

private List<Subjects> subjects; 

那麼你可以使用

school.addStudent("ABC", Arrays.asList(Subjects.Maths, Subjects.English)); 
+1

如果你想以後添加科目給學生,這個答案是不正確的,因爲由'Arrays.asList(...)'返回的'List'不能在結構上修改。應該包裹或者在構造函數中或該列表傳遞新的'ArrayList',即'新的ArrayList <>參數時(Arrays.asList(Subjects.English,Subjects.Maths))'。 –

1

這裏是我會做:

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); 
    } 
}