如何在包含不同对象的ArrayList中添加对象组的结尾

时间:2017-04-14 20:48:06

标签: java arraylist indexof

我应该为addcourse创建一个ArrayList方法。 Arraylist有学生和课程。课程在学生之后添加到该学生的最后。例如,Arraylist可以包含(Student1, Course1, Course2, Student2, Course1, Course3)。当我想将Course3添加到Student1时,它应该在Course2之后,但在Student2之前。

addcourse方法应该有接口: void addcourse(Student s, Course c). 首先选择我想要添加课程的学生和课程。如何在Student2中找到ArrayList的索引。

1 个答案:

答案 0 :(得分:0)

你在使用ArrayList做什么?您只需向Student类添加ArrayList<Course> courses即可。

例如:

public class Student{
    public ArrayList<Course> courses = new Arraylist<Course>;

    //Other stuff

    public void addCourse(Course c){
        courses.add(c);
    }
}

修改

由于这对OP不起作用,我还提供了一个在问题的约束下工作的方法。步骤:

  • 找到Student
  • 的索引
  • 找到 next Student
  • 的索引
  • 将新的Course放在下一个Student
  • 之前

如果你的ArrayList被称为list,那么这样的东西就可以了:

    public void addCourse(Student student, Course course){
        int studentIndex = -1;
        int nextStudentIndex = -1;

        for(int i=0; i<list.size(); i++){
            if(!(list.get(i) instanceof Student)){
                continue;
            }

            if(list.get(i).equals(student)){
                studentIndex = i;
                continue;
            }

            if(studentIndex != -1 && nextStudentIndex == -1){
                nextStudentIndex = i;
            }
        }

        list.add(nextStudentIndex, course);
    }