0

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 all the other elements are null, then I need to pass that object and get the index of the element which contains that object

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
user1912520
  • 31
  • 1
  • 1
  • 3
    Why do you think you need to override a function at all? – bmargulies Dec 25 '12 at 14:12
  • because I need to get the index by passing an object which only contains a single element, which is the ID while all the other elements of the object is null – user1912520 Dec 25 '12 at 14:14
  • yes I need to search an object from the arraylist – user1912520 Dec 25 '12 at 14:15
  • There is something I don't understand: can you have several elements of your array with the same id? If yes, can't you use a `Map` instead with your identifiers as keys? – fge Dec 25 '12 at 14:22

1 Answers1

5

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);
}
Community
  • 1
  • 1
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49