JAVA8 自定义实现Comparable接口类、Comparator接口
开发过程中如果我们想让某个对象是可比较大小的,那么需要实现Comparable这个接口的方法来满足自然排序。
举例:我们根据鼠标的价格从低到高进行排序,如果价格一样再根据鼠标的名称来进行从低到高排序。
class Mouse implements Comparable{ String goodsName; int price; public Mouse(String name,int price){ this.goodsName = name; this.price = price; } @Override public int compareTo(Object o) { if (o instanceof Mouse){ Mouse mouse = (Mouse) o; if (this.price > mouse.price){ return 1; }else if(this.price < mouse.price){ return -1; }else { //价格一样按照货物名称排 return -this.goodsName.compareTo(mouse.goodsName); } }else { throw new RuntimeException("传入的不是鼠标类型"); } } @Override public String toString() { return "Mouse{" + "goodsName='" + goodsName + '\'' + ", price=" + price + '}'; } }
@Test public void test1(){ Mouse[] li = new Mouse[5]; li[0] = new Mouse("XiaoMi",20); li[1] = new Mouse("Logitech",50); li[2] = new Mouse("lenove",30); li[3] = new Mouse("dell",25); li[4] = new Mouse("Huawei",50); Arrays.sort(li); System.out.println(Arrays.toString(li)); }
这里如果价格一样按照货物名称从高到底进行排序,输出结果为
[Mouse{goodsName='XiaoMi', price=20}, Mouse{goodsName='dell', price=25}, Mouse{goodsName='lenove', price=30}, Mouse{goodsName='Logitech', price=50}, Mouse{goodsName='Huawei', price=50}]
现在我的Mouse类已经写好了,但是我在排序的时候想要先按照货物名称从高到低,再根据价格从低到高排序,那我们实现的CompareTo方法就不管用了,这里需要使用实现Cpmparator接口来满足定制排序。
@Test
public void test1(){
Mouse[] li = new Mouse[6];
li[0] = new Mouse("XiaoMi",20);
li[1] = new Mouse("Logitech",50);
li[2] = new Mouse("Lenove",30);
li[3] = new Mouse("Dell",25);
li[4] = new Mouse("Huawei",50);
li[5] = new Mouse("Huawei",52);
Arrays.sort(li, new Comparator<Mouse>() {
@Override
public int compare(Mouse o1, Mouse o2) {
int i = -o1.goodsName.compareTo(o2.goodsName);
if (i !=0){
return i;
}else {
int j = o1.price - o2.price;
if (j>0){
return 1;
}else {
return -1;
}
}
}
});
System.out.println(Arrays.toString(li));
}
输出结果为
[Mouse{goodsName='XiaoMi', price=20}, Mouse{goodsName='Logitech', price=50}, Mouse{goodsName='Lenove', price=30}, Mouse{goodsName='Huawei', price=50}, Mouse{goodsName='Huawei', price=52}, Mouse{goodsName='Dell', price=25}]