好吧,我正在建立一所大学的在线注册系统。这是一个用java编写的相当基本的系统,因此无需担心数据库问题。我的问题是:我有一类名为Course的对象。每门课程都有一个属性列表(id,time,instructor等)。然后,每个用户都有一个可以添加或删除的课程对象的arraylist(或者你可以安排)。我的问题是如何为每个学生/用户创建一个arraylist?如果目录中有一个单独的arraylist可供选择,那么它是否有益?关于这个问题的任何建议都会有所帮助。如果你想看到我的代码示例到目前为止让我知道,我将编辑我的帖子以包含它。
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
答案 0 :(得分:1)
无需使用地图;您自己表达了正确的关系:"每个用户 ArrayList
"。表达has-a关系的方式是使用实例字段:
public class Student {
private final List<Course> courses = new ArrayList<>();
//write methods that operate on courses, or make courses public
....
如果您以任何方式关注课程的属性,将课程表示为课程对象是最简单的。但是,如果您只需要知道课程ID,或者您需要存储大量学生,则可以通过将课程存储为整数或短片并在静态表格中查找来节省空间。
答案 1 :(得分:0)
我会有三个单独的课程,学生和入学。
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
}
学生
public class Student {
private final int studentID;
private final String name;
private Set<Course> studentCourses;
public Student(int studentId, String name) {
this.name = name;
this.studentID = studentId;
}
public String getName(){
return this.name;
}
public int getStudentId(){
return this.studentID;
}
void addCourse(Course course) {
if(!studentCourses.contains(course)){
studentCourses.add(course);
}
else{
studentCourses.remove(course);
studentCourses.add(course);
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + this.studentID;
hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (this.studentID != other.studentID) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
}
注册
class Enrollment{
//This Map will group student with the same name
private Map<String, List<Student>> enrollment;
public Enrollment(Student student){
if(enrollment.containsKey(student.getName())){
enrollment.get(student.getName()).add(student);
}else
{
List<Student> newStudent = new ArrayList<Student>();
newStudent.add(student);
enrollment.put(student.getName(), newStudent);
}
}
public void addCourse(Student student, Course course){
try{
List<Student> studentSameName = enrollment.get(student.name);
for(Student studentEntry : studentSameName){
if(studentEntry.getStudentId() == student.getStudentId()){
studentEntry.addCourse(course);
}
}
}catch(NullPointerException e){
//student does not exist
//TODO Add Logic
}
}
public void removeStudent(Student student){
//TODO Add Logic
}
}