Java之text

好久没用过比较器了,算是练手吧

/**
 * 学生对象类
 * 
 * @author Willie
 * 
 */
class Student {


    private String name;// 姓名
    private int age;// 年龄
    private int height;// 身高


    public Student() {
    }


    public Student(String name, int age, int height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }


    @Override
    public String toString() {
        return "姓名:" + name + " 年龄:" + age + " 身高:" + height;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }


    public int getHeight() {
        return height;
    }


    public void setHeight(int height) {
        this.height = height;
    }
}

/**
 * Student对象比较器
 * 
 * @author Willie
 */
class StudentComparator implements Comparator<Student> {


    @Override
    public int compare(Student s1, Student s2) {
        // 比较两个学生的姓名,在字典顺序中,s1在s2的前面则返回-1,反之亦然
        int tmpN = s1.getName().compareTo(s2.getName());
        if (tmpN < 0)
            return -1;
        else if (tmpN > 0)
            return 1;
        // 当s1和s2的名字一样时,比较他们的年龄
        else {
            // 若s1的年龄小于s2则返回-1,反之亦然
            int tmpA = s1.getAge() - s2.getAge();
            if (tmpA < 0)
                return -1;
            else if (tmpA > 0)
                return 1;
            // 当s1和s2的姓名、年龄都一样时,比较他们的身高
            else {
                // 若s1的身高小于s2则返回-1,反之亦然
                int tmpH = s1.getHeight() - s2.getHeight();
                if (tmpH < 0)
                    return -1;
                else if (tmpH > 0)
                    return 1;
                // 当s1和s2的姓名、年龄和身高都一样时就返回0
                return 0;
            }
        }
    }
}
// 测试代码

public static void main(String[] args) {
        Student stu0 = new Student("张三", 12, 150);
        Student stu1 = new Student("张三", 13, 150);
        Student stu2 = new Student("张三", 12, 160);
        Student stu3 = new Student("李四", 12, 150);
        Student stu5 = new Student("张二", 12, 150);
        Student stu6 = new Student("张四", 12, 150);
        Student[] stus = new Student[] { stu0, stu1, stu2, stu3, stu5, stu6 };
        Arrays.sort(stus, new StudentComparator());
        for (Student student : stus) {
            System.out.println(student);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值