Better Way To Find Index Of Item From ArrayList
Answer :
You can use list.indexOf()
, but in order to make it work, you need to override equals
and hasCode
of your POJO
.
By default, two objects will be considered equal if they have the same reference. You can overwrite equals
to work for your case:
public boolean equals(Object o) { if (!(o instanceof POJO)) { return false; } POJO other = (POJO) o; return name.equalsIgnoreCase(other.getName()); }
Overridding equals would suggest you override hashCode
. For example:
public int hashCode() { return name.hashCode(); }
Finding element in this way where complexity would be give you BIG-O (n). I think if you Map that would gives you better result.
HashMap
would be better choice. - Where Complexity would be O(1).
If you need to search on a string value you should use a HashMap
instead of ArrayList
.
Comments
Post a Comment