Issues with binarySearch implementation
When I tried to write the following line:
int foundIndex = Collections.<K>binarySearch(keys, key);
error displayed: Parameterized method of <K>binarySearch(List<? extends Comparable<? super K>>, K)
type is
Collections
not applicable for arguments(List<K>, K)
What does the above error mean and what did I do wrong in my code?
// 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 class
import java.util.Comparator;
@Override
public int compare(K key1, K key2)
{
return -1;
}
}
Your problem is that it FastGetListMM<K, V>
implements Comparable<K>
but Collections.<K>binarySearch(list, value)
expects a list Comparable<K>
.
This K
is to be implemented Comparable<K>
, not FastGetListMM
. If you want to use Collections.<K>binarySearch(keys, key)
, you need to FastGetListMM
implement List<Comparable<K>>
, not Comparable<K>
- and make sure all elements in FastGetListMM
are in ascending order.
source to share