Is there anyway to search a binary array of Objects, not for a complete element of the array, but rather for an element containing a specific field value? At present the only way I see of doing it is to create a new "Entry" object to search for - and because of the compareTo implementation it doesnt matter what the second field "intial" contains.
Is there a way of implementing a binary search so that I can simply search surname.element fields directly - given that the array is already sorted by surname?
I am aware that I could iterate through the array searching the fields of each element but in this case I need to use a binarySearch.
public class Entry implements Comparable<Entry> { //implements allows sorting
public String surname;
public char intial;
public Entry(String surname, String initial, int number) {
this.surname = surname.toUpperCase();
this.intial = initial.toUpperCase().charAt(0); // if whole name entered
//takes first letter only
}
@Override
public int compareTo(Entry o) {
else {
return this.surname.compareTo(o.surname);
}
}
public class EntryList {
public static main(String[] args) {
List<Entry> directory = new ArrayList<Entry>();
directory.add(new Entry("surname", "intial"));
int i = Collections.binarySearch(directory, new Entry("surname", " ")); //doesnt matter whats in intial field
}
}
}