Is there any way to implement binary search in a ArrayList with objects? In this example the ArrayList will be sorted with the field 'id'.
class User{
public int id;
public string name;
}
ArrayList<User> users = new ArrayList<User>();
sortById(users);
int id = 66
User searchuser = getUserById(users,id);
How would the "User getUserById( ArrayList users, int userid )" look like if I it should return the user with a specified id using binary search? Is this even possible?
Best Answer
The Object Ordering article of The Java Tutorials has an example of writing your own
Comparator
in order to perform comparisons on custom types.Then, the
ArrayList
(or any otherList
), the key to find, along withComparator
can be passed into theCollections.binarySearch
method.Here's an example: