gpt4 book ai didi

java - binarySearch 实现问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:54 24 4
gpt4 key购买 nike

当我尝试编写以下行时:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com