Related problems and examples of Java array query [original]
In the process of array query, we sometimes encounter some problems. Let's follow the author to answer these problems.
The binarysearch () method of the arrays class can use the binary search method to search the specified array to obtain the specified object. This method returns the index value of the element to be searched. The binarysearch () method provides a variety of overloaded forms to meet the search needs of various types of arrays. The binarysearch () method has two parameter types.
(1) Binarysearch (object [] a.object key) where a represents the array to be searched and key represents the value to be searched. If the key is included in the array, the index of the search value is returned; Otherwise, - 1 or "-" (insertion point) will be returned. The insertion point is the point where the search key will be inserted into the array, that is, the first element index greater than this key. We must understand why the value of index is negative here.
Example 1: query array elements. The example code is as follows:
In the above code, the value of variable index is the index position of element "8" in indexes 0 ~ 1. The value of index is' - 'because the element' 8 'does not exist in the specified range. If the array is sorted, the element "8" should precede 25, so the insertion point should be the index value 2 of element 25, so the value of index is - 2.
Example 2: find the index position of element 4 in the array. code:
The running result is: the index position of 4 is: 2
(2) Binarysearch (object []. A, int fromindex, int toindex, object key) this method retrieves an element within the specified range. a: The array to be retrieved; Fromindex: the index at the beginning of the specified range (included); toindex: the index at the end of the specified range (not included); key: the elements to be searched. Before using this method, the array should also be sorted to obtain the accurate index value.
Example 3: find the index position of the element "77" in the array STR of the specified range. The code is as follows:
The operation result is: 1
Note: if the specified range is greater than or equal to the length of the array, an ArrayIndexOutOfBoundsException will be reported.
If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!