In a Java program, I have an array of objects. Each object has a field that is an ID number and all fields are public (no getters and setters). The array is ordered by ID number which is an integer. I don’t want to use a for loop or a similar technique to loop through every object because the array may be large. So,
- what search algorithm will do this efficiently, and…
- is there a handy Java method that will do this search for me so I
don’t have to write it myself?
Either use java.util.Arrays.binarySearch() (if its an array of primitives or you have a Comparator) or java.util.Collections.binarySearch() (if you have a non-array collection of your own Comparable object).
It sounds like Arrays.binarySearch would fit your problem better. Write a proper java.util.Comparator that understands your ordering.