如何使整数具有可比性

时间:2018-03-31 00:38:22

标签: java comparable compareto

我正在尝试使用类似的界面对随机生成的数组进行排序,但我收到错误消息:

不兼容的类型:int []无法转换为Comparable []

int [] list;
list = new int[n];

for(int i=0;i<n;i++){
    list[i]=(int)(1+n*Math.random());
}
sortingoutsorts.bubble(list);
}
private static void swap(Object [] list, int x, int y)
{
    Object temp=list[x];
    list[x]=list[y];
    list[y]=temp;
}
public static void bubble(Comparable [] list)
{
    boolean done=false;
    while(!done)
    {
        done=true;
        for(int i=0; i+1<list.length; i++)
            if(list[i].compareTo(list[i+1])>0)
            { swap(list,i,i+1); done=false; }
    }
}

1 个答案:

答案 0 :(得分:6)

int是原始数据类型,您无法在原始数据类型上实现Comparable。您希望使用其Wrapper类Integer,它已经实现了Comparable。

但是,如果您不想更改变量的类型,则可以更改

if(list[i].compareTo(list[i+1])>0)

if(list[i] > list[i+1])

并更改气泡签名以接受任何int数组。