簡體   English   中英

錯誤:選擇類型中的方法排序(Comparable [])不適用於參數(int [])

[英]Error: the method sort (Comparable []) in the type Selection is not applicable for the arguments (int[])

這是我嘗試寫出Selection排序時遇到的錯誤。 有人可以指出我在做什么錯。 我的代碼如下。 謝謝!

    public class Selection
    {
        static void sort(Comparable[] a)
    {
    int N = a.length;
    for (int i = 0; i < N; i++)
    {
    int min = i;
     for (int j = i+1; j < N; j++)
     if (less(a[j], a[min]))
     min = j;
     exch(a, i, min);
     }
     }
     private static boolean less(Comparable v, Comparable w)
     { 
     return v.compareTo(w) < 0;   
     }
    private static void exch(Comparable[] a, int i, int j)
    { 
     Comparable temp = a[i];
     a[i] = a[j];
     a[j] = temp;
 }

public static void main(String args[])
{

    int[] ys = {3,4,5,5,22,4,66,4444,33,3,656,544,4};
    Selection.sort(ys);
}


}

int是原始類型,因此無法實現任何接口。 這就是為什么無法將int []傳遞給期望Comparable []的方法的原因。

您可以通過將ys更改為Integer的數組(即Integer [])來克服此錯誤,因為Integer實現了Comparable。

int是原始數據類型。 它不是一個類,並且沒有實現Comparable

您應該改用確實實現Comparable Integer

可比對象適用於對象,並且您知道int不是對象。 int[]解析為singular object而不是對象數組。

如果將ys定義為Integer[] ,則將獲得預期的對象數組。

正如前面的提問者所提到的,您不能將int應用於Comparable ,但是如果您仍然想使用基元並使用Integer而不是Comparable ,后者會實現Comparable ,並且編譯器會將int轉換為Integer

static void sort(int[] a)
{
    int N = a.length;
    for (int i = 0; i < N; i++)
    {
        int min = i;

        for (int j = i+1; j < N; j++)
            if (less(a[j], a[min]))
                min = j;

        exch(a, i, min);
    }
}

private static boolean less(Integer v, Integer w)
{
    return v.compareTo(w) < 0;
}

private static void exch(int[] a, int i, int j)
{
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM