繁体   English   中英

Java-在2D数组中搜索数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM