Is it possible to search an array of objects in Java by a private attribute with the Array.binarySearch method? I was thinking there must be something similar to the sorting technique, where you create a class that implements Comparator and pass this in to Array.sort, but I can’t seem to find anything (maybe there is something where instead of the compareTo method you just return the attribute used in the search)??
To be clear I have an array of anonymous Station objects, and this is passed to another class where I want to search the array for the name of the stations, which can be returned via a getName().
Any help would be much appreciated!
Yes – in fact it uses
Comparator, which you specified in your answer!If you have a look over the implementations of the
binarySearchmethod in the API, you come across binarySearch(T[] a, T key, Comparator c) which:You can implement the Comparator however you like, and so can use it to compare the private attributes alluded to in your question.
Edit responding to comment: The
Tis a generic parameter, meaning it can be anything, so long as it’s the same in every position it appears. In this case, it means that the first parameter must be an array of the second parameter’s type. Or in other words, if you’re sorting an array ofTs (Stations in your case) then you need to pass in an instance of that class (Stationhere) to act as the object to compare against. This key argument will always be passed in as one of the arguments to the comparator’s compare method.So I suspect in your case you were passing in a String representing the station name; you should instead pass in an instance of
Stationwhich has the appropriate name.