问题是这样出现的:我有一个array
private final String[] enabled_view = {"location", "sensor", "train_time", "file_walk"};
然后我想要找到每个对于的索引值,于是不知道怎么查的就找到了Arrays.binarySearch这个方法,之前这样跑了都没有问题
int sensor_index = Arrays.binarySearch(enabled_view, "sensor");
int train_time_index = Arrays.binarySearch(enabled_view, "train_time");
直到今天我去加一个功能,之前屎山的坑才暴雷:
int fileWalk_index = Arrays.binarySearch(enabled_view, "file_walk");
这句话的返回值突然变成了-1
于是翻文档:
/**
* Searches the specified array for the specified object using the binary
* search algorithm. The array must be sorted into ascending order
* according to the
* {@linkplain Comparable natural ordering}
* of its elements (as by the
* {@link #sort(Object[])} method) prior to making this call.
* If it is not sorted, the results are undefined.
* (If the array contains elements that are not mutually comparable (for
* example, strings and integers), it <i>cannot</i> be sorted according
* to the natural ordering of its elements, hence results are undefined.)
* If the array contains multiple
* elements equal to the specified object, there is no guarantee which
* one will be found.
*
* @param a the array to be searched
* @param key the value to be searched for
* @return index of the search key, if it is contained in the array;
* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
* <i>insertion point</i> is defined as the point at which the
* key would be inserted into the array: the index of the first
* element greater than the key, or {@code a.length} if all
* elements in the array are less than the specified key. Note
* that this guarantees that the return value will be >= 0 if
* and only if the key is found.
* @throws ClassCastException if the search key is not comparable to the
* elements of the array.
*/
public static int binarySearch(Object[] a, Object key) {
return binarySearch0(a, 0, a.length, key);
}
划重点:
according to the natural ordering
If it is not sorted, the results are undefined.
所以,这个东西很大程度是用在数字的身上的,虽然它写的是object对象
总结:不要把Arrays.binarySearch用在非数字上!用在数字上的话请先排好序