Comparable和Comparator的使用
public class Goods implements Comparable{
String name;
double price;
public Goods() {
}
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;
}
@Override
public String toString() {
return "Goods{" +
"name=" + name +
", price=" + price +
'}';
}
//指明商品比较大小的方式:按照价格从低到高排序,名称从高到低排序
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
//方式一
Goods g1 = (Goods) o;
if (this.getPrice()>g1.getPrice()){
return 1;
}else if(this.getPrice()<g1.getPrice()){
return -1;
}else {
return -this.name.compareTo(g1.name);
}
//方式二
//return Double.compare(this.getPrice(), g1.getPrice());
}
throw new RuntimeException("传入的数据类型不一致");
}
}
public class CompareTest {
/*
自然排序
Comparable接口的使用举例:
1.像String、包装类等实现了Comparable接口,重写了compareTo(),从小到大排列。
2.重写compareTo(obj)的规则:
如果当前对象this大于形参对象obj,则返回正整数,
如果当前对象this小于形参对象obj,则返回负整数,
如果当前对象this等于形参对象obj,则返回零
3.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo()
*/
@Test
public void test1(){
String[] arr = new String[]{"AA","CC","BB"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
@Test
public void test2(){
Goods[] goods = new Goods[4];
goods[0] = new Goods("dellMouse",35);
goods[1] = new Goods("huaweiMouse",50);
goods[2] = new Goods("xiaomiMouse",15);
goods[3] = new Goods("mechrevMouse",15);
Arrays.sort(goods);
System.out.println(Arrays.toString(goods));
}
@Test
public void test3(){
String[] arr = new String[]{"AA","CC","BB"};
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof String && o2 instanceof String){
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("输入的数据类型不正确");
}
});
System.out.println(Arrays.toString(arr));
}
/*
定制排序:规则和自然排序;类似
*/
@Test
public void test4(){
Goods[] goods = new Goods[4];
goods[0] = new Goods("dellMouse",35);
goods[1] = new Goods("huaweiMouse",50);
goods[2] = new Goods("xiaomiMouse",15);
goods[3] = new Goods("huaweiMouse",225);
//指明商品比较大小的方式:按照名称从高到低排序,价格从低到高排序
Arrays.sort(goods, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Goods && o2 instanceof Goods){
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
if (g1.getName().equals(g2.getName())) {
return Double.compare(g1.price,g2.price);
}else {
return -g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("传入的参数类型不一致");
}
});
System.out.println(Arrays.toString(goods));
}
}