Java中的排序
Comparable接口:自然排序
案例:将产品按照价格从低到高排序,如果价格相同,则按名称ASCII大小排序
public class Test {public static void main(String[] args) {Product[] arr = new Product[]{new Product(new StringBuilder("产品1"), 5000),new Product(new StringBuilder("产品2"), 5555),new Product(new StringBuilder("产品3"), 6000),new Product(new StringBuilder("产品4"), 5000)};Arrays.sort(arr);for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}
}
class Product implements Comparable {private StringBuilder name;private double price;public Product() {}public Product(StringBuilder name, double price) {this.name = name;this.price = price;}public StringBuilder getName() {return name;}public void setName(StringBuilder name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Product{" +"name=" + name +", price=" + price +'}';}@Override// 从小到大排序public int compareTo(Object o) {if (this == o) {return 0;}if (o instanceof Product) {Product p = (Product) o;// 两个价格换个位置就可以实现从大到小排序了int num = Double.compare(this.getPrice(), p.getPrice());if (num != 0) {return num;}// 价格相同再比较名称// 两个名称换个位置就可以实现从大到小排序了return this.getName().compareTo(p.getName());}throw new RuntimeException("异常");}
}
运行结果
Comparator接口:定制排序
public class Test {public static void main(String[] args) {Product[] arr = new Product[]{new Product(new StringBuilder("产品1"), 5000),new Product(new StringBuilder("产品2"), 5555),new Product(new StringBuilder("产品3"), 6000),new Product(new StringBuilder("产品4"), 5000)};Comparator comparator = new Comparator(){@Override// 按照价格从高到低排序public int compare(Object o1, Object o2) {if (o1 instanceof Product && o2 instanceof Product) {Product p1 = (Product) o1;Product p2 = (Product) o2;return Double.compare(p2.getPrice(), p1.getPrice());}throw new RuntimeException("异常");}};// 将定制排序传入sort中,相当于覆盖之前已有的排序方式Arrays.sort(arr, comparator);for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}
}
运行结果