java-不要把Arrays.binarySearch用在非数字上!

问题是这样出现的:我有一个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 &gt;= 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用在非数字上!用在数字上的话请先排好序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值