Reputation:
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!
Upvotes: 0
Views: 7156
Reputation: 103847
Yes - in fact it uses Comparator
, which you specified in your answer!
If you have a look over the implementations of the binarySearch
method in the API, you come across binarySearch(T[] a, T key, Comparator c) which:
Searches the specified array for the specified object using the binary search algorithm.
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 T
is 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 of T
s (Station
s in your case) then you need to pass in an instance of that class (Station
here) 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 Station
which has the appropriate name.
Upvotes: 5
Reputation:
Thanks, eventually got it working using
Arrays.binarySearch(allStations,new Station("nameofstationhere"),new StationCompare())
which is probably a bad way as I'm creating a new Station object for comparison... but it works and not sure how to do it using just the string...
Upvotes: 0
Reputation: 22456
If the array of stations is not already sorted by the station names, it makes no sense sorting and searching for every query. It is faster to do a linear search in this case. However, if you can sort the array and then perform multiple binary searches, it is worthwhile. Implement a comparator such as the following, and use it for both sorting (Arrays.sort(..)) and searching (Arrays.binarySearch(..)):
private class StationNameComparator implements Comparator<Station> {
public int compare(Station s1, Station s2) {
return s1.getName().compareTo(s2.getName());
}
}
Note that I assume that the names are non-null and unique.
Upvotes: 0
Reputation: 285057
Yes, there's an overload that takes a comparator. Remember that you can only use binarySearch
if the array is already sorted.
Upvotes: 2