Java - 在二维数组中搜索数组
Java - Searching a 2D array for an array
Java中是否有任何内置方法或库可以在二维数组中搜索数组?
示例:
public static final short[][] roots = new short[][] {
{0x02, 0x3c, 0x81, 0xcc, 0xe8, 0xe7, 0xc6, 0x4f},
{0x09, 0x99, 0xbf, 0x90, 0x0b, 0xd5, 0xc2, 0x97},
....
};
// Array to find
short[] itemArray = {0x09, 0x99, 0xbf, 0x90, 0x0b, 0xd5, 0xc2, 0x97};
检查 itemArray
在 roots
中是否可用的最佳方法是什么?
更新: roots
是一个排序数组。无论如何,搜索可以利用 Arrays.binarySearch
?我想 Comparator<short[]>
能帮上忙(怎么写)?
for (short[] arr1 : roots){
if (Arrays.equals(arr1, itemArray)){ return true;}
}
return false;
Arrays.equals(arr1, arr2) 是一个内置函数,用于比较一维数组以进行相等性检查。
你可以使用它。
for(short [] arr : roots) {
if (Arrays.equals(arr1, itemArray)) {
// arr1 matches the itemArray
// you can also use a counter variable to return the row number
}
}
int index = Arrays.binarySearch(roots, itemArray, (arr1, arr2) -> {
// your compare algorithm goes here.
});
if (index != -1) {
// get your array with roots[index].
}
Java中是否有任何内置方法或库可以在二维数组中搜索数组?
示例:
public static final short[][] roots = new short[][] {
{0x02, 0x3c, 0x81, 0xcc, 0xe8, 0xe7, 0xc6, 0x4f},
{0x09, 0x99, 0xbf, 0x90, 0x0b, 0xd5, 0xc2, 0x97},
....
};
// Array to find
short[] itemArray = {0x09, 0x99, 0xbf, 0x90, 0x0b, 0xd5, 0xc2, 0x97};
检查 itemArray
在 roots
中是否可用的最佳方法是什么?
更新: roots
是一个排序数组。无论如何,搜索可以利用 Arrays.binarySearch
?我想 Comparator<short[]>
能帮上忙(怎么写)?
for (short[] arr1 : roots){
if (Arrays.equals(arr1, itemArray)){ return true;}
}
return false;
Arrays.equals(arr1, arr2) 是一个内置函数,用于比较一维数组以进行相等性检查。
你可以使用它。
for(short [] arr : roots) {
if (Arrays.equals(arr1, itemArray)) {
// arr1 matches the itemArray
// you can also use a counter variable to return the row number
}
}
int index = Arrays.binarySearch(roots, itemArray, (arr1, arr2) -> {
// your compare algorithm goes here.
});
if (index != -1) {
// get your array with roots[index].
}