自然排序
class day21_22 implements Comparable {
private String name;
private double price;
public day21_22() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public day21_22(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "day21_22{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Object o) {
if( o instanceof day21_22){
day21_22 goods = (day21_22)o;
if(this.price > goods.price){
return 1;
}else if(this.price < goods.price){
return -1;
}else{
return 0;
}
}
throw new RuntimeException("传入的数据类型不一致");
}
}
定制排序
public class compareTest {
public static void main(String[] args) {
String[] arr = new String[]{"aa","bb","cc","dd","rr","ff"};
Arrays.sort(arr,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof String && o2 instanceof String){
String s1 = (String)o1;
String s2 = (String)o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}
}