我有一个int的2D数组,并且想要使用Arrays.binarySearch()查找带有特定第二个元素的第一个数组,而不考虑第一个元素的值,但是我不知道正确的方法语法。
我虽然应该与带有自定义比较器的Arrays.sort()中使用的语法相同,但是显然我不正确:)
这里有一些示例代码:
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] ));
我得到的错误是:
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))
有人可以为我提供Arrays.binarySearch()的正确语法吗?
谢谢!
@@ Andreas很友善地提供了此解决方案:
在那个泛型中,T是一个int [],这意味着第二个参数必须为int [],但您正在传递int。更改第二个参数从2到新的int [] {0,2}。 ---然后确保您捕获了从binarySearch(...)返回值,否则有什么意义。
我还没有意识到,即使您输入了精确的值作为目标参数,也可以忽略它,或者只使用目标的属性进行二进制搜索。在我的示例中,我正在寻找索引1处的值为2的任何int [],因此索引0处的值无关紧要;我们可以将其设置为任何内容。