当前位置: 代码迷 >> Eclipse >> Java数组排序 貌似还没懂 嘿嘿,该怎么解决
  详细解决方案

Java数组排序 貌似还没懂 嘿嘿,该怎么解决

热度:495   发布时间:2016-04-23 13:33:35.0
Java数组排序 貌似还没懂 嘿嘿
package ch2;

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
Shape[] shapes=new Shape[10];
  //赋值省略 shape 是一个对象,里面有个面积area属性,我要按照属性面积排序,用下面的
  //就是那个比较的不会写,我还是新手啦,自己看道理有点难,
  //还是请大神直接写出来,以后举例不叫容易 嘿嘿谢啦
Arrays.sort(shape);
System.out.print("排序后的面积是:");
for (int i = 0; i < shape.length; i++) {
if (shape[i] != null) {
System.out.print("\t" + shape[i].getArea());
}
}
System.out.println("程序退出!");
}
}


------解决方案--------------------
Java code
修改你的Shape类实现Comparable接口,如class Shape implements Comparable<Shape> {    ...    publit int compareTo(Shape s) {        if (s == null) return -1;        return this.getArea() - s.getArea(); //如果是属性,直接this.area - s.area    }}或者,用Arrays.sort带上比较器参数,如Arrays.sort(shapes, new Comparator<Shape>() {    public int compare(Shape s1, Shape s2) {        if (s1 == null) {            return (s2 == null ? 0 : 1);        } else if (s2 == null) {            return -1;        }        return s1.getArea() - s2.getArea();    }});
------解决方案--------------------
伸手党啊,你自己把Comparator弄明白了以后不就都会写了。
Arrays.sort(shapes, new Comparator<Shape>() {
@Override
public int compare(Shape s1, Shape s2) {
//如果getArea()返回的是个对象比如Double类的可以用:
//return s1.getArea().compareTo(s2.getArea());
//返回的是原生类型的就自己去比较:
double d = s1.getArea() - s2.getArea();
if(d > 0) {
return 1;
} else if (d < 0) {
return -1;
} else {
return 0;
}
}
});
------解决方案--------------------
用另一个函数:
public static <T> void sort(T[] a, Comparator<? super T> c)

类似这样:
Arrays.sort(shape, new Comparator(){
public int compare(Shape o1, Shape o2) {
// 自行处理关于 o1 和 o2 的比较。
}
public boolean equals(Object obj){
return this.equals(obj);
}
});
  相关解决方案