我正在尝试使用可比接口(interface)对随机生成的数组进行排序,但我收到错误消息:
不兼容的类型: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; }
}
}
最佳答案
int 是原始数据类型,您不能在原始数据类型上实现 Comparable。你想改用它的 Wrapper 类,Integer ,它已经实现了 Comparable。
但是,如果您不想更改变量的类型,您可能会更改
if(list[i].compareTo(list[i+1])>0)
到
if(list[i] > list[i+1])
并更改气泡签名以接受任何 int 数组。
关于java - 如何使整数具有可比性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583113/