[英]Java - Searching a 2D array for an array
Java中是否有內置方法或庫可在2D數組中搜索數組?
例:
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
itemArray
中可用的最佳方法是什么?
更新: 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].
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.