创建一个购物车类,根据购物车的价格和名字排序。
方式一使用价格和名字升序
-
实现Comparable接口
方式二使用价格和名字降序
-
匿名内部类Comparator
package com.Demo.exe1;
import java.util.Arrays;
import java.util.Comparator;
public class TestGoods {
public static void main(String[] args) {
Goods g1 = new Goods("红楼梦1", 100);
Goods g2 = new Goods("红楼梦2", 100);
Goods g3 = new Goods("红楼梦3", 300);
Goods[] all = new Goods[3];
all[0]=g2;
all[1]=g1;
all[2]=g3;
Arrays.sort(all);
System.out.println(Arrays.toString(all));
System.out.println("=========");
//第二种方式,使用匿名内部类
//o1.getPrice()-o2.getPrice()为升序 或者 o2.getPrice()-o1.getPrice()为降序
// 当o1.getPrice()=o2.getPrice()的时候比较书名字,根据书名降序排序
Arrays.sort(all, new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
int num =(int) (o2.getPrice() - o1.getPrice())*1000;
return num==0?o2.getName().compareTo(o1.getName()):num;
}
});
System.out.println(Arrays.toString(all));
}
}
//第一种方式实现Comparable接口
class Goods implements Comparable<Goods>{
private String name;
private double price;
public Goods(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;
}
//重写compareTo方法,this - o 是升序
@Override
public int compareTo(Goods o) {
int i = (int) (this.price - o.price);
return i==0?this.getName().compareTo(o.getName()):i;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}