一、JAVA实现排序的两种方式
自然排序:java.lang.Comparable
定制排序:java.utli.Comparator
二、实现
实现Comparable接口重写compareTo方法
import java.util.Arrays;
class Compar1 implements Comparable{
private String name;
private int price;
public Compar1(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Compar1{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Object o) {
if(o instanceof Compar1){
Compar1 comp=(Compar1) o;
if (this.price>comp.price)
return -1;
else if(this.price<comp.price)
return 1;
else
return 0;
}
else
throw new RuntimeException("类型错误");
}
}
public class ComparTest1<com> {
public static void main(String[] args) {
Compar1[] com=new Compar1[5];
com[0]=new Compar1("111",24);
com[1]=new Compar1("222",44);
com[2]=new Compar1("333",12);
com[3]=new Compar1("444",33);
com[4]=new Compar1("555",4);
Arrays.sort(com);
System.out.println(Arrays.toString(com));
}
}
实现Comparator接口,重写compare方法
import java.util.Arrays;
import java.util.Comparator;
public class ComparTest2 {
public static void main(String[] args) {
Compar1[] com=new Compar1[5];
com[0]=new Compar1("111",24);
com[1]=new Compar1("222",44);
com[2]=new Compar1("333",12);
com[3]=new Compar1("444",33);
com[4]=new Compar1("555",4);
Arrays.sort(com, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Compar1&& o2 instanceof Compar1){
Compar1 c1=(Compar1) o1;
Compar1 c2=(Compar1) o2;
if(c1.getName().equals(c2.getName())){
return -Integer.compare(c1.getPrice(), c2.getPrice());
}
else
return c1.getName().compareTo(c2.getName());
}
throw new RuntimeException("数据类型不一致!");
}
});
System.out.println(Arrays.toString(com));
}
}
三、区别
需要反复使用使用comparable,突然需要使用的用comparator;