ArrayList.remove() is not removing an object

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

    You must correctly override the equals() method for both Student and Instructor classes.

    When overriding equals, it is good to override hashCode() as well. new Student(name, id, GPA);

    For example, something like this:

    public boolean equals(Object o) {
      if (!(o instanceof Student)) {
        return false;
      }
      Student other = (Student) o;
      return name.equals(other.name) && id.equals(other.id) && GPA == other.GPA;
    }
    
    public int hashCode() {
      return name.hashCode();
    }
    

    This way, you give a chance to the ArrayList figure out which object correspond to the one you passed as a parameter when deleting. If you don't override the above methods, it will use the default implementations in Object, which compare memory addresses which are definitely different as you remove a new Student object.

    You can read even more information about the 2 methods in the javadocs for Object.

提交回复
热议问题