比较器comparable与comparator的使用

  在Java学习和使用里,工具类与算法类(collections和Arrays)也是我们使用比较多的,在它们里面就包含了comparable与comparator这两种比较器。

一.比较器的分类与概念

  1.comparable内部比较器:这是元素自身以来就有先人规定好的默认比较规则;

  2.comparator外部比较器:这是我们根据具体需要而自定义的第三方比较规则;(当有外部比较器时元素的自带内部比较器就会被取代)

注:放回的正数负数,依赖于根据比较规则两个元素位置的差。

二.使用内部比较器与外部比较器(排序,只能操作List)

  例:

设置的外部比较器:

package com.lovo.bean;

import java.util.Comparator;

public class StudentComparator implements Comparator<StudentBean>{


    public int compare(StudentBean o1, StudentBean o2) {

        if(o1.getScore() > o2.getScore()){//设置根据成绩进行排序大的在前面
            return -1;
        }else if(o1.getScore() < o2.getScore()){
            return 1;
        }
        return 0;
    }

}

主函数

import java.util.Collections;
import com.lovo.bean.StudentBean;
import com.lovo.bean.StudentComparator;

public class TestCollections {

    public static void main(String[] args) {//比较器专用例子
        ArrayList<StudentBean> lst = new ArrayList<StudentBean>();
        lst.add(new StudentBean("zhang3",30,74));
        lst.add(new StudentBean("li4",22,67));
        lst.add(new StudentBean("wang5",23,67));
        lst.add(new StudentBean("zhao6",24,80));
        lst.add(new StudentBean("chen7",26,56));
        
        Collections.sort(lst);//自带内部比较器
        System.out.println(Collections.max(lst));//求最大
        System.out.println(Collections.min(lst));//求最小
        Collections.reverse(lst);//反转
        Collections.shuffle(lst);//混排--随机打乱排序  
        Collections.sort(lst,new StudentComparator());//提供外部比较器
        for(StudentBean stu : lst){
            System.out.println(stu);
        }
    }
}                    

posted on 2017-01-02 11:45  八两石头  阅读(1486)  评论(0编辑  收藏  举报

导航