public class ComparableTest {
public static void main(String[] args) {
String[] arr = new String[] {"TT", "CC", "YY", "AA", "aa", "zz", "ii"};
Arrays.sort(arr);
// 默认排序
System.out.println(Arrays.toString(arr)); // [AA, CC, TT, YY, aa, ii, zz]
// 自然排序方法,实现Comparable接口的compareTo方法
Product[] products = new Product[5];
products[0] = new Product("C产品一", 6999);
products[1] = new Product("D产品二", 4999);
products[2] = new Product("A产品三", 5999);
products[3] = new Product("R产品四",9999);
products[4] = new Product("T产品五", 6199);
Arrays.sort(products);
System.out.println(Arrays.toString(products));
// [Product [name=产品二, price=4999],
// Product [name=产品三, price=5999],
// Product [name=产品五, price=6199],
// Product [name=产品一, price=6999],
// Product [name=产品四, price=9999]]
// 定制排序Comparator
Comparator<Product> comparator = new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
return o1.getName().compareTo(o2.getName());
};
};
Arrays.sort(products, comparator);
System.out.println(Arrays.toString(products));
// [Product [name=A产品三, price=5999],
// Product [name=C产品一, price=6999],
// Product [name=D产品二, price=4999],
// Product [name=R产品四, price=9999],
// Product [name=T产品五, price=6199]]
}
}
class Product implements Comparable<Object> {
private String name;
private int price;
public Product() {
}
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + "]";
}
// @Override
// public int compareTo(Product o) {
// return o.price - this.price; // 从大到小
// }
@Override
public int compareTo(Object o) {
if (o == this) {
return 0;
}
if (o instanceof Product) {
Product p = (Product) o;
return this.price - p.price; // 从小到大
}
throw new RuntimeException("类型不匹配");
}
}
Java排序Comparable和Comparator
于 2024-03-19 20:48:01 首次发布