我试图创建一个学生arraylist到一个课程类,以便当一个学生被添加时,arraylist增加。这是我到目前为止的代码:
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Saj
*/
public class Course {
private String courseName;
private int noOfStudents;
private String teacher;
public static int instances = 0;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*/
public Course(){
instances++;
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
}
/**
* Constructor with parameters
* @param noOfStudents integer
* @param courseName String with the Course name
* @param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
}
}
我不确定如何实现数组列表。有人能指出我正确的方向。
答案 0 :(得分:0)
只需为您的班级添加属性
List<Student> students;
在构造函数中,初始化此列表:
students = new ArrayList<>();
创建将学生添加到列表的方法:
public boolean addStudent(Student stud) {
if (stud == null || students.contains(stud)) {
return false;
}
students.add(stud);
return true;
}
另请查看https://docs.oracle.com/javase/8/docs/api/java/util/List.html以获取列表文档。 问题是,你想在构造函数中添加学生吗?如果是这样,请将参数添加到构造函数
public Course(int noOfStudents, String courseName,
String teacher, List<Student> students){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
this.students = new Arraylist<>(students);
}