Question

For an array of objects, is it possible to implement a binary search method (preferably with Arrays.binarySearch) with multiple key values needed to be matched?

Say, the object type of an array has a constructor with obj(String a, String b, int c). How can I implement Arrays.binarySearch to find the object that has the same values of whatever variables String a and String b stands for as I specified? (i.e. something like Arrays.binarySearch(arrayName, value for varX, value for varY))

Of course, it makes much more sense to add an unique identifier to each object, but in this case, I can't.

Should I do something with the compareTo in the object class (as I already did for sorting)?

Any help is much appreciated.

Thank you and have a nice day!

Was it helpful?

Solution

Here we are using Comparable to compare the objects.

Steps to follow:

  • implement Comparable for your custom class
  • in compareTo() method compare the values based on a and b
  • now sort the array before binary search
  • pass a dummy object having values set for a and b in binarySearch() method.
  • That's all

Try this simple code:

import java.util.Arrays;

public class DemoTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MyClass[] array = new MyClass[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = new MyClass(String.valueOf(i), String.valueOf(i + 10), i + 20);
        }

        // sort before binary search
        Arrays.sort(array);
        int index = Arrays.binarySearch(array, new MyClass("5", "15"));
        if (index > -1) {
            System.out.println("found at " + index);
        } else {
            System.out.println("not found");
        }

        index = Arrays.binarySearch(array, new MyClass("6", "15"));
        if (index > -1) {
            System.out.println("found at " + index);
        } else {
            System.out.println("not found");
        }

    }
}

class MyClass implements Comparable<MyClass> {
    private String a;
    private String b;
    private int c;

    public MyClass(String a, String b) {
        this.a = a;
        this.b = b;
    }

    public MyClass(String a, String b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }   


    @Override
    public int compareTo(MyClass o) {
        int result = this.a.compareTo(o.a);
        if (result == 0) {
            return this.b.compareTo(o.b);
        } else {
            return result;
        }
    }

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