与Collections.binarySearch的通用列表参数出错

时间:2014-08-13 23:38:24

标签: java generics

尝试在Java中编写Python样式bisect_right,并使用List参数的泛型类型:

import java.util.*;

class Util {

    /* eqv to python's bisect_right. That is: return insertion point, but
    if key is in list, insertion point is to right of it.
    */
    //public static int bisect_right(List<String> list, String x) { //>> type specific
    public static <E> int bisect_right(List<E> list, E x) {
        int idx = Collections.binarySearch(list, x);     

        if (idx >= 0) { // key contained in list
            idx = idx + 1;
        }           
        else {
            idx = -idx -1; 
        }
        return idx;
    }
}   

编译器抱怨没有找到匹配Collections.binarySearch的方法。我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题在于Ethe Collections.binarySearch method的调用需要Comparable<? super E>,但您在E上没有这个限制。

E方法上添加绑定到bisect_right声明的内容。

public static <E extends Comparable<? super E>> int bisect_right(List<E> list, E x) {

<E extends Comparable<E>>似乎也在这里工作。)