ArrayList.remove() is not removing an object

后端 未结 4 561
滥情空心
滥情空心 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:22

    You need to Override equals and hashcode methods for collections to work properly.

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (!(obj instanceof Student))
            return false;
        Student other = (Student) obj;
        return id == null ? false : id.equals(other.id);//Compare Id if null falseF
    }
    

    Since you are only using ArrayList there is hashcode method will not be used but it is still good practice to provide it.

     @Override
    public int hashCode() {
        return id == null ? 0 : id.hashCode();
    }
    

提交回复
热议问题