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?
The Object Ordering article of The Java Tutorials has an example of writing your own
Comparatorin order to perform comparisons on custom types.Then, the
ArrayList(or any otherList), the key to find, along withComparatorcan be passed into theCollections.binarySearchmethod.Here’s an example: