Question

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
    }
}


}
Was it helpful?

Solution

Your question doesn't make much sense.

Binary search works on sorted collection, so of course your element have to be comparable. Define your compareTo and equals methods to consider only the surname field, and then you can use binarySearch.

EDIT: I'm still not sure whether you are asking about the usage of the library function binarySearch or about the implementation of a custom binary search function.

For the first case the answer is no, there is no such overloading of binarySearch in the API. Generally in an array you want to search by entity equality, because in the intended use case of this method you already have the entity you are searching for, but you don't know if it is contained in the target array, and on which index can be found. However you want to search an entity by a key, which might sign that you are misusing ArrayList and binarySearch; a SortedMap would fit better for this task.

On the other hand, if you stick to ArrayList, than of course you can implement yourself a method like binary search, which uses only your surname field for matching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top