Search code examples
javabinary-search

Java Arrays.binarySearch on a two-dimensional int[][] with Comparator.comparingInt()


I have a 2D array of int and want to use Arrays.binarySearch() to find a the first array with a specific second element, irrespective of the value of the first element but I don' I am unable to figure out the correct syntax.

I though it should be the same syntax as used in Arrays.sort() with a custom comparator, but evidently I am incorrect :)

Here is some sample code:

int[][] a = new int[][]{ {1,2}, {2,4}, {3,6}, {9, -1} } ;

//first sort the array
Arrays.sort(a, Comparator.comparingInt((int[] i) -> i[1]));

// after sorting the array is now: {9,-1}, {1,2}, {2,3}, {3,6}
//this won't compile, should return 0 since a[0] is the only element with a second element equal to 2
int index = Arrays.binarySearch(a, 2, Comparator.comparingInt( (int[] i) -> i[1] ));

The error I get is:

Error:(14, 15) java: no suitable method found for binarySearch(int[][],int,java.util.Comparator<int[]>)
    method java.util.Arrays.<T>binarySearch(T[],T,java.util.Comparator<? super T>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: java.io.Serializable
        upper bound(s): java.io.Serializable,int[],java.lang.Object)
    method java.util.Arrays.<T>binarySearch(T[],int,int,T,java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

Could someone help me with the correct syntax for Arrays.binarySearch()?

Thanks!


Solution

  • @Andreas was kind enough to offer this solution:

    In that generic, T is an int[], which means that the second parameter must be an int[], but you're passing an int. Change second parameter from 2 to new int[] { 0, 2 }. --- Then make sure you capture the return value from binarySearch(...), otherwise what's the point.

    I hadn't realized that even though you pass in an exact value as the target parameter, it's possible to ignore it, or just use a property of the target, for the binary search. In my example I was looking for any int[] with where the value at index 1 is 2, so it doesn't matter what value we have at index 0; we can set it to anything.