Which function should I override when using indexOf() function

后端 未结 1 1613
花落未央
花落未央 2021-01-26 07:33

Which function should I override when using the indexOf() function in java. I have a array list, then I take in an input as the ID and create a object which contains the ID and

相关标签:
1条回答
  • 2021-01-26 08:00

    The equals() method

    public boolean equals(Object o) {
      if (o instanceof MyObject) {
        //id comparison
        MyObject mo = (MyObject)o;
        return mo.id.equals(id);
      }
      return false;
    }
    

    Change MyObject to your class.

    Remember to change hashCode() as well as @Hovercraft points out. equals and hashCode go together (read the javadoc for them). Else you might run into some nasty and possibly hard to find bugs.

    An example:

    With java 7+ you can do this:

    public int hashCode() {
        return java.util.Objects.hashCode(id);
    }
    
    0 讨论(0)
提交回复
热议问题