关于interface Comparator??

soarweiss 2003-09-29 11:45:56
我想通过用一个类实现Comparator接口,覆写其中的compare(),来改变Array.sort对int的排序方式(改成从大到小排) 可编译器提示
在 Arrays.sort(n,new intSort());出错
错误信息:method sort(int[],p_learn.IntSort) not found in class java.util.Arrays....
为什么?

下面是code:
----------------------------------------------------------------
package p_learn;
import java.util.*;

class IntSort implements Comparator{
public int compare(Object o1,Object o2){
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
return i1.compareTo(i2)> 0 ? -1 : (i1.compareTo(i2) == 0) ? 0 : 1;

}

}

public class Array2 {

public Array2() {}
public static void main(String[] args)
{

int [] n ={2,6,3,2,6};
Arrays.sort(n,new IntSort());
}
...全文
52 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cowboy1114 2003-09-29
  • 打赏
  • 举报
回复
你如果要在sort中使用Comparator做为参数,则sort中的第一个参数类型必须为对象数组,不能为基本类型数组。
cowboy1114 2003-09-29
  • 打赏
  • 举报
回复
package p_learn;
import java.util.*;

class IntSort implements Comparator{
public int compare(Object o1,Object o2){
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
return i1.compareTo(i2)> 0 ? -1 : (i1.compareTo(i2) == 0) ? 0 : 1;

}

}

public class Array2 {

public Array2() {}
public static void main(String[] args)
{

Integer [] n ={new Integer(2),new Integer(6),
new Integer(3),new Integer(2),new Integer(6)};
Arrays.sort(n,new IntSort());
for(int i=0;i<n.length;i++)
System.out.println(n[i]);
}
}
honkyjiang 2003-09-29
  • 打赏
  • 举报
回复
static void sort(Object[] a, Comparator c)
Sorts the specified array of objects according to the order induced by the specified comparator.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧