当我尝试编写以下行时:
int foundIndex = Collections.<K>binarySearch(keys, key);
它显示错误:参数化方法<K>binarySearch(List<? extends Comparable<? super K>>, K)
类型
Collections
不适用于参数 (List<K>, K)
上述错误是什么意思,我的代码哪里做错了?
// Comparator used to sort elements; may be null if elements are Comparable
public final Comparator<K> cmp;
{
super(new ArrayList<K>(), new ArrayList<V>());
cmp = new MyComparator<K>();
}
// Use the given comparator to sort the keys
//super(new ArrayList<K>(), new ArrayList<V>());
this.cmp = cmp;
}
{
if(!(key instanceof Comparable) && cmp == null)
throw new RuntimeException("The key is not instance of Comparable or comparator object is null");
}
public int indexOf(K key)
{
int foundIndex = Collections.<K>binarySearch(keys, key);
return foundIndex;
}
public int compareTo(K otherKey)
{
int result = 0;
for(int i = 0; i < keys.size(); i++)
{
result = ((Comparable<K>) keys.get(i)).compareTo(otherKey);
}
return result;
}
MyComparator 类
import java.util.Comparator;
@Override
public int compare(K key1, K key2)
{
return -1;
}
}
最佳答案
你的问题是FastGetListMM<K, V>
正在实现 Comparable<K>
但是那个Collections.<K>binarySearch(list, value)
期待一个 Comparable<K>
的列表 .
是K
应该实现 Comparable<K>
, 不是 FastGetListMM
.如果你想使用 Collections.<K>binarySearch(keys, key)
你需要FastGetListMM
实现List<Comparable<K>>
而不是 Comparable<K>
- 并确保 FastGetListMM
中的所有项目升序排列。
关于java - binarySearch 实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29983036/