Jon Kho wrote:
Rob Prime wrote:Also, List.indexOf uses the equals method to find the object. Since you haven't overridden that, it still uses Object's equals method - which only uses == for checking.
Now that may be what you want, but I thought I'd warn you to prevent future problems.
Hi Rob,
I am just curious about the future problem which you have mentioned. is it because that it uses the function of "checking" and not "searching"? in actually check I prefer to use the "search" function. In fact i came across this method, from here.
Is it better to use this one than the one i am currently using?
Thanks for your concern.
Jon
indexOf uses the equals method, and Collections.binarySearch uses the compareTo method (or a custom comparator). Now String has great implementations for both, but if you want to search a List<Show> and return an element, you have two options:
- provide the same object reference as is already in the list
- override equals
If you don't override equals, the following will always print -1:
That's because equality is based on reference equality.
You can do a search to find good examples of equals methods. Don't forget to override hashCode() as well.