"运算符>未定义参数类型K,K"我一直得到这个,我无法解决它

0 java algorithm

package apc.dastruc.algorithms;

public class BinarySearch<K>{

    public void bubbleSorting(K[] haystack){
        int j = 0;
        int i = 0;
        int temp;

            while(j < (haystack.length - j)){
                    while (i < (haystack.length - 1)){
                        if(haystack[i] > haystack[i + 1]){
                            temp = haystack[i];
                            haystack[i] = haystack[i - 1];
                            haystack[i - 1] = temp;
                        }
                    }
            }

    }

    public int search(K[] haystack, K needle){
        bubbleSorting(haystack);

        int i = haystack.length / 2;

        while(i > 0 && i > haystack.length){
            if(needle.equals(haystack[i])){
                return i;
            }else if(needle < haystack[i]){
                i--;
            }else if(needle > haystack[i]){
                i++;
            }
        } 

        return -1; //no match is found
    }



}
Run Code Online (Sandbox Code Playgroud)

问题是我们需要让它们成为泛型.所以我不能真正将他们的类型更改为int.

Mik*_*rry 5

如果K实现了Comparable,那么你可以这样做:

        if(needle.compareTo(haystack[i]) == 0){
            return i;
        } else if(needle.compareTo(haystack[i]) > 0){
            i--;
        } else {
            i++;
        }
Run Code Online (Sandbox Code Playgroud)

您的代码还希望强制K实现Comparable以执行此操作,即:

public class BinarySearch<K extends Comparable<K>>
Run Code Online (Sandbox Code Playgroud)

我想你可能想看看Comparable界面.