I have a class which implements comparable to compare and sort an array of its instances on the basis of one of the class variables. Now I want to be able to search the array of this class objects using Arrays.binarySearch. For that, will overiding the equals method be enough?
I have a class which implements comparable to compare and sort an array of
Share
No,
binarySearchworks on “more or less” comparisons rather than equality comparisons. If you’re implementingComparableproperly, such that it obeys the interface consistently, in particular returning 0 when items are equal, that should be all that’s required. (Alternatively, you can specify aComparator.)Of course, the array has to be ordered appropriately before
binarySearchwill work…