类如下
- Java code
public static class __9_7_Person implements Comparator<__9_7_Person> { private int height; private int weight; public __9_7_Person(int height, int weight) { this.height = height; this.weight = weight; } public int compare(__9_7_Person p1, __9_7_Person p2) { if (p1.height != p2.height) { return p1.height - p2.height; } else { return p1.weight - p2.weight; } } }
创建对象如下
- Java code
__9_7_Person p[] = {new __9_7_Person(60, 100), new __9_7_Person(70, 150), new __9_7_Person(56, 90), new __9_7_Person(75, 190), new __9_7_Person(60, 95), new __9_7_Person(68, 110),};
但是当调用 Arrays.sort(p) 的时候抛出了异常:Exception in thread "main" java.lang.ClassCastException: ch_9$__9_7_Person cannot be cast to java.lang.Comparable
------解决方案--------------------
是继承Comparable接口
并重写compareTo方法
------解决方案--------------------
关于Arrays.sort(Object[])其实可以按照指定的排序规则进行排序,默认情况下按照自然顺序(即对象实现了compareble接口,Arrays回调compareble的compare方法进行排序),但是Arrays也支持用户指定比较规则进行排序,就是sort(T[] a, Comparator<? super T> c)这个静态方法(详见API)
修改了了下楼主的代码如下:
- Java code
package sortutil.test;import java.util.Arrays;import java.util.Comparator;public class __9_7_Person implements Comparator<__9_7_Person> { private int height; private int weight; public __9_7_Person(int height, int weight) { this.height = height; this.weight = weight; } public int compare(__9_7_Person p1, __9_7_Person p2) { if (p1.height != p2.height) { return p1.height - p2.height; } else { return p1.weight - p2.weight; } } public String toString(){ return "\nHeigth:"+height +"||"+"Weight:"+weight; } public static void main(String[] args) { __9_7_Person[] p = {new __9_7_Person(60, 100), new __9_7_Person(70, 150), new __9_7_Person(56, 90), new __9_7_Person(75, 190), new __9_7_Person(60, 95), new __9_7_Person(68, 110), }; Arrays.sort(p,new __9_7_Person(0,0));//new __9_7_Person(0,0)被转成comparator System.out.println(Arrays.toString(p)); }}