简体   繁体   中英

Java - Searching a 2D array for an array

Are there any builtin method or library in Java to search for an array within a 2D array?

Example:

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};

What's the best way to check if itemArray is available in roots ?

Update: roots is a sorted array. Anyway the search could take advantage of Arrays.binarySearch ? I suppose Comparator<short[]> could help (how to write one)?

for (short[] arr1 : roots){
   if (Arrays.equals(arr1, itemArray)){ return true;}
}
return false;

Arrays.equals(arr1, arr2) is a built in function to compare 1D arrays for equality check.

you can use it.

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].
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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