ArrayList.remove() is not removing an object

后端 未结 4 574
滥情空心
滥情空心 2020-12-09 05:37

I know this is a messy implementation, but I basically have this code (I wrote all of it), and I need to be able to remove a student or instructor from the list when using t

4条回答
  •  忘掉有多难
    2020-12-09 06:12

    Overriding the equals method of Student and Instructor will work:

    Here is an example for the Student class:

    public boolean equals(Object other){
        if(other == null) return false;
        if(other == this) return true;
        if(!(other instanceof Student)) return false;
        Student otherStudent = (Student)other;
        return otherStudent.id.equals(this.id);
    }
    

    You may also want to override hashCode():

    public String hashCode(){
        return new HashCodeBuilder(17, 31).
            append(name).
            append(id).
            toHashCode();
    }
    

提交回复
热议问题