一:自然排序:Comparable
实现了comparable的对象直接就可以成为一个可以比较的对象。
定义一个类实现Comparable接口,并重写compareTo方法,compareTo方法中要指明排序方式
class Person implements Comparable{
private String name;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(String name) {
this.name = name;
}
@Override
public int compareTo(Object o) {
if (o instanceof Person) {
Person p = (Person) o;
return this.name.compareTo(p.name);
}
throw new RuntimeException("异常");
}
}
之后在main方法中进行测试
public static void main(String[] args) {
String [] arr = {"史蛋","二度","香肠","倒萨"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
输出结果为
二:定制排序:Comparator
与类中的compareTo方法相似,但这里用到了两个参数。
“-”号代表逆序,自然排序为顺序
public static void main(String[] args) {
String [] arr = {"史蛋","二度","香肠","倒萨"};
// Arrays.sort(arr);
Arrays.sort(arr, new Comparator() {
@Override
public int compare(String o1, String o2) {
if (o1 instanceof String && o2 instanceof String) {
String s1 = o1;
String s2 = o2;
return -o1.compareTo(o2);
}
throw new RuntimeException("异常");
}
});
System.out.println(Arrays.toString(arr));
}
}
输出结果:
三:练习:自定义泛型及Compare自定义排序,对bag按照价格及品牌名称进行排序
定义Bags类实现Comparable接口,并重写compareTo方法
class Bages implements Comparable{
private String name;
private double price;
public Bages(String name, double price) {
this.name = name;
this.price = price;
}
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;
}
@Override
public String toString() {
return "Bages{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Object o) {
if (o instanceof Bages) {
Bages bages = (Bages) o;
if (this.price > bages.price) {
return 1;
}else if (this.price < bages.price) {
return -1;
}else {
//名字排序,按照字母顺序(-this表示逆序)
return this.name.compareTo(bages.name);
}
}else {
throw new RuntimeException("异常");
}
}
}
main方法进行测试
public static void main(String[] args) {
Bages[] arr = new Bages[4];
arr[0] = new Bages("loose", 52000);
arr[1] = new Bages("loosa", 23000);
arr[2] = new Bages("zippo", 12000);
arr[3] = new Bages("ziaoop", 2600);
// 自然排序
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
System.out.println("*********************");
// 定制排序
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Bages o1, Bages o2) {
if (o1 instanceof Bages && o2 instanceof Bages) {
Bages b1 = o1;
Bages b2 = o2;
if (b1.getName().equals(b2.getName())) {
return -Double.compare(b1.getPrice(),b2.getPrice());
}else {
return Double.compare(b1.getPrice(),b2.getPrice());
}
}
throw new RuntimeException("异常");
}
});
System.out.println(Arrays.toString(arr));
}
}