先来说说基本的认识:comparable与comparator 两者都是接口,实现的方法都是对对象进行排序。 comparable 这个词是以able结尾的,说明是一种能力,一种属性,可参见 Serializable,继承了该接口就可以实现序列化了。那么继承 comparable 并且重写compareTo方法,就可以让该类的对象拥有与其他同类对象的比较能力。 这是该类对象所具备的能力。
而comparator相当与从第三方的角度进行对对象的比较,类的本身不需要继承该接口。
那么什么情况下会需要comparator接口呢?
1.所比较的类没有继承comparable,但是又需要比较的时候
2.所比较的类没有继承comparable并且也重写了比较方法,但是在业务上该比较方法不适用,需要自己定制一个。
代码分析:
1.comparable
先定义一个商品类,继承comparable,重写compareTo方法
public class Goods implements Comparable {
private String name;
private 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 int compareTo(Object o) {
if(o instanceof Goods ){
Goods goods =(Goods)o;
if (this.price > goods.price) {
return 1;
}else if(this.price < goods.price){
return -1;
}else
//return 0;
return this.name.compareTo(goods.name);
}
throw new RuntimeException("传入的数据类型不一致");
}
}
public class Demo {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
List<Goods> list = new ArrayList<>();
Goods goods = new Goods("内裤", 33);
Goods goods2 = new Goods("丁字裤", 31);
Goods goods3 = new Goods("长裤", 32);
list.add(goods);
list.add(goods2);
list.add(goods3);
System.err.println(goods.compareTo(goods2));
//该方法会调用定义的比较器
Collections.sort(list);
list.stream().forEach(Element-> System.err.println(Element.getName()));
// 丁字裤、 长裤、内裤
}
}
2.
public class Demo {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
List<Goods> list = new ArrayList<>();
Goods goods = new Goods("内裤", 33);
Goods goods2 = new Goods("丁字裤", 31);
Goods goods3 = new Goods("长裤", 32);
list.add(goods);
list.add(goods2);
list.add(goods3);
Collections.sort(list, new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
// TODO Auto-generated method stub
return 0;
}
});
}
}
public class Demo {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
List<Goods> list = new ArrayList<>();
Goods goods = new Goods("内裤", 33);
Goods goods2 = new Goods("丁字裤", 31);
Goods goods3 = new Goods("长裤", 32);
list.add(goods);
list.add(goods2);
list.add(goods3);
Compare compare = new Compare();
int a = compare.compare(goods, goods2);
System.err.println(a);
}
}
class Compare implements Comparator<Goods>{
@Override
public int compare(Goods o1, Goods o2) {
// TODO Auto-generated method stub
if(o1.getPrice() > o2.getPrice())
return 1;
else
return 0;
}
}