Java学习笔记-Compare

Compare内置引用数据类型比较:

1、整数、小数、Integer、Float、Doubble类型,直接比较基本数据大小。

2、字符比较unicode码之差。

3、字符串:

1)如果其中一个是另外一个的起始开始的子串,返回长度之差。

2)否则返回第一个不相等的unicode之差。

 

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;
    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

4、Date 根据日期的长整形进行比较。

public int compareTo(Date anotherDate) {
    long thisTime = getMillisOf(this);
    long anotherTime = getMillisOf(anotherDate);
    return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}

2、冒泡排序泛型方法

public class SortUtils {

    /**
     * 数组按大到小排序(使用泛型方法)
     * @param arr
     * @param <T>
     */
    public static <T extends Comparable> void maoPaoSortByMaxToMin(T[] arr){
        int len = arr.length;
        for (int i=0;i<len-1;i++){ //趟数

            for (int j=0;j<len-1;j++){
                if(arr[j].compareTo(arr[j+1])<0){//次数
                    T temp = arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;

                }
            }
        }
    }
    /**
     * List按大到小排序
     * @param list
     * @param <T>
     */
    public static <T extends Comparable> void maoPaoSortByList(List<T> list){
        //todo
    }
}
 

3、自定义比较器

public class MyGoods {
    //名称
    public String name;
    //价格
    public double price;
    //收藏量
    public int fav;

    public MyGoods(String name, double price, int fav) {
        this.name = name;
        this.price = price;
        this.fav = fav;
    }

    public static void main(String[] args){
        List<MyGoods> list =new ArrayList<>();
        list.add(new MyGoods("玉溪",20,100));
        list.add(new MyGoods("中华",90,200));
        list.add(new MyGoods("长白山",10,1000));

        Collections.sort(list,new GoodsPriceComparator());
    }
}

 
public class GoodsPriceComparator implements java.util.Comparator<MyGoods> {
    @Override
    public int compare(MyGoods o1, MyGoods o2) {
        return o1.price- o2.price>0?1:(o1.price==o2.price?0:-1);
    }
}

       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值