user4833678
user4833678

Reputation:

binarySearch implementation issues

When I tried to write the following line:

int foundIndex = Collections.<K>binarySearch(keys, key);

it shows the error: The parameterized method <K>binarySearch(List<? extends Comparable<? super K>>, K) of type Collections is not applicable for the 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;
    }

}

Upvotes: 3

Views: 150

Answers (2)

Raniz
Raniz

Reputation: 11113

Your problem is that FastGetListMM<K, V> is implementing Comparable<K> but that Collections.<K>binarySearch(list, value) is expecting a list of Comparable<K>.

It is K that should implement Comparable<K>, not FastGetListMM. If you want to use Collections.<K>binarySearch(keys, key) you need FastGetListMM to implement List<Comparable<K>> and not Comparable<K> - and make sure that all the items in FastGetListMM are arranged in ascending order.

Upvotes: 1

Benjy Kessler
Benjy Kessler

Reputation: 7616

To use that implementation of binary search you need K to implement comparable there is another function that receives the comparable itself. In your case you need to call Collections.<K>binarySearch(keys, key, new MyComparator());

Upvotes: 0

Related Questions