尝试用 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
匹配的方法。我做错了什么?
最佳答案
问题是 E
需要是Comparable<? super E>
调用the Collections.binarySearch
method ,但你在 E
上没有这个限制.
将其添加到 E
的声明中在您的bisect_right
上方法。
public static <E extends Comparable<? super E>> int bisect_right(List<E> list, E x) {
(<E extends Comparable<E>>
似乎也可以在这里工作。)
关于java - Collections.binarySearch 的通用列表参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297907/