想实现整数数组从大到小排序,使用Comparator,写了如下代码,为什么编译不通过啊,那里有问题?
[code]
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
int[] a = {1,6,3,7,2,9};
Arrays.sort(a, new Cmp());
}
}
class Cmp implements Comparator<Integer> { public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}[/code]
[code]
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
int[] a = {1,6,3,7,2,9};
Arrays.sort(a, new Cmp());
}
}
class Cmp implements Comparator<Integer> { public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}[/code]
解决方案 »
- 无法调用servlet /relogin.jsp的service()方法
- 二进制数据转换
- 有哪位高手知道怎么用JAVA实现组件的圆形布局啊
- java如何调用C#编写的动态库?急...............
- 急!!!jar文件在xp下象使用exe文件一样方便,在2000下为何不能使用?
- J2SE V1.4.2 如何安装,急死了!
- java请教 如何用正则获取字符串
- 类型转化问题2
- 举例说明他们的区别,写个记事本程序用哪个好?
- 下午要到金蝶软件去面试,这个公司怎么样呀?参与有分!
- org.eclipse.swt.SWTException: Invalid thread access??
- 如何设置java环境变量
static void sort(int[] a)
static void sort(int[] a, int fromIndex, int toIndex)
public static <T> void sort(T[] a,
Comparator<? super T> c)
Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.
Parameters:
a - the array to be sorted.
c - the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used.
Throws:
ClassCastException - if the array contains elements that are not mutually comparable using the specified comparator.
See Also:
Comparator
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
Integer[] a = {1,6,3,7,2,9};
Arrays.sort(a, new Cmp());
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
class Cmp implements Comparator<Integer> { public int compare(Integer o1, Integer o2) {
int i=o2-o1;
if(i>0)
return 1;
if(i<0)
return -1;
else
return 0;
}
}
当然,当非范型函数遭遇范型函数,内建类型数组遭遇自定义类型数组,具体编译器会怎么处理偶也没钻研过,说不上来了。但有一点是肯定的,即便那样可以,你用int[]的效率也不太会比Integer[]高,因为前者在排序的过程中,在每一步调用Comparator的compare的时候,都要对两个参数各进行一个装箱,然后,从compare返回,再来一次拆箱
//随第一个参数小于、等于或大于第二个参数而分别返回负整数、零或正整数
无非就是重载那个int compare(对象1,对象2)的时候返回值改一下就好了。