常用类-Java比较器
一、Comparable接口
Java中的对象,正常情况只能进行比较 == 或 !=不能使用
> 或 < 的,但是在实际开发中有需要进行对象的比较
comparable接口的使用举例:
1.像String、包装类等实现了comparable接口,重写了comparableTo(obj)方法,给出了比较两个对象大小的方式
2.像String 、包装类重写comparableTo(obj)方法以后,进行了从小到大的排列
3.重写comparableTo(obj)的规则
如果当前对象this大于形参对象obj,则返回正整数
如果当前对象this小于形参对象obj,则返回负整数
如果当前对象this等于形参对象obj,则返回零
4.对于自定义类来说,如果需要排序,我们可以让自定义类实现comparable接口,重写compareTo()
在comparableTo(obj)方法中指明如何排序
测试单元代码如下:
点击查看代码
@Test
public void test1(){
Goods[] arr1 = new Goods[5];
arr1[0] = new Goods("lenovoMouse",35);
arr1[1] = new Goods("huaweiMouse",65);
arr1[2] = new Goods("dellMouse",43);
arr1[3] = new Goods("xiaomiMouse",21);
arr1[4] = new Goods("mircsoftMouse",65);
Arrays.sort(arr1);
System.out.println(Arrays.toString(arr1));
}
Goods类代码如下:
点击查看代码
package com.Tang.StringDay02;
public class Goods implements Comparable{
private String name;
private double price;
public Goods() {
}
public Goods(String name, int 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 "name="" + name + """ +
", 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 -this.name.compareTo(goods.name);
//按价格排序方式二
// return Double.compare(this.price,goods.price);
}
throw new RuntimeException();
}
}
运行结果图
二、Comparator实现定制排序
点击查看代码
@Test
public void test3(){
Goods[] arr1 = new Goods[5];
arr1[0] = new Goods("lenovoMouse",35);
arr1[1] = new Goods("huaweiMouse",65);
arr1[2] = new Goods("dellMouse",43);
arr1[3] = new Goods("huaweiMouse",21);
arr1[4] = new Goods("mircsoftMouse",65);
//指明商品比较大小的方式:按名称从低到高排序,名称相同按价格从高到低排
Arrays.sort(arr1, 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() == g2.getName()){
return -Double.compare(g1.getPrice(),g2.getPrice());
}
else{
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("输入数据类型不一致");
}
});
System.out.println(Arrays.toString(arr1));
}
运行结果图