Java基础之Comparable与Comparator概述
自然排序Comparable
对于自定义类进行排序
要实现Comparable接口,重写compareTo() 方法,如果不重写,像使用Arrays.sort()排序就会报错
package com.che.lambda; import java.util.Objects; /** * @author cheyuhang on 2021/4/23 */ public class Good implements Comparable{ private String name; private Double price; public Good(String name, Double price) { this.name = name; this.price = price; } public Good() { } 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 boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Good good = (Good) o; return Objects.equals(name, good.name) && Objects.equals(price, good.price); } @Override public int hashCode() { return Objects.hash(name, price); } @Override public String toString() { return "Good{" + "name='" + name + '\'' + ", price=" + price + '}'; } @Override public int compareTo(Object o) { if (o instanceof Good){ //判断传递参数是否属于商品 Good good=(Good) o; if(this.price >good.price){ return 1; }else if(this.price <good.price) { return -1; }else { return 0; } } throw new RuntimeException("传入数据类型不一致"); } }
定制排序Comparator
使用场景:当类没有实现Comparable接口或者实现了Comparable接口,但不符合我期望的排序规则时进行使用
@Test public void test02() { Good[] arr=new Good[5]; arr[0] =new Good("zhangsan",234.0); arr[1] =new Good("lisi",2343.0); arr[2] =new Good("wangwu",2354.0); arr[3] =new Good("zhaoliu",2334.0); arr[4] =new Good("tianqi",2347.0); System.out.println(Arrays.toString(arr)); Arrays.sort(arr, new Comparator<Object>() @Override public int compare(Object o1, Object o2) { if (o1 instanceof Good && o2 instanceof Good){ Good g1=(Good) o1; Good g2=(Good) o2; return Double.compare(g1.getPrice(),g2.getPrice()); //return g1.compareTo(g2); } throw new RuntimeException("数据类型不一致"); } }); System.out.println(Arrays.toString(arr)); }
到此这篇关于Java基础之Comparable与Comparator详解的文章就介绍到这了,更多相关Java Comparable与Comparator内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)