Comparable接口和Comparator接口实战

一 Comparable介绍

Comparable:定义默认比较规则。

Comparable——可比较的。

  • 实现该接口表示:这个类实例是可以比较的,可进行自然排序。

  • 定义了默认的比较规则。

  • 其实现类需要实现compareTo()方法

  • compareTo()方法返回正数表示大,负数表示小,0表示相等。

二 Comparator介绍

Comparator:定义临时比较规则。

Comparator接口——比较工具接口

用于定义临时比较规则,而不是默认比较规则。

其实现类需要实现compare()方法。

Comparator和Comparable都是Java集合框架的成员。

三 实战

1 Student

package CollectionPart;


import java.util.HashSet;
import java.util.Set;


/**
* 学生类
*
* @author Administrator
*/
public class Student implements Comparable<Student> {


    public String id;


    public String name;


    public Set<Course> courses;


    public Student( String id, String name ) {
        this.id = id;
        this.name = name;
        this.courses = new HashSet<Course>();
    }


    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


    @Override
    public boolean equals( Object obj ) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Student))
            return false;
        Student other = (Student) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }


    //@Override
    public int compareTo( Student o ) {
        // TODO Auto-generated method stub
        return this.id.compareTo(o.id);
    }
}

2 StudentComparator

package CollectionPart;


import java.util.Comparator;


public class StudentComparator implements Comparator<Student> {


   @Override
   public int compare(Student o1, Student o2) {
      // TODO Auto-generated method stub
      return o1.name.compareTo(o2.name);
   }


}

3 测试类

package CollectionPart;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;


/**
* 将要完成
* 1 通过Collections.sort()方法,对Integer泛型List进行排序
* 2 对String泛型的List进行排序
* 3 对其他类型泛型的List进行排序,以Student为例。
*/
public class CollectionsTest {


    /**
     * 1.通过Collections.sort()方法,对Integer泛型List进行排序
     * 创建Integer泛型List,插入十个100以内的不重复随机整数,
     * 调用Collections.sort()方法对其进行排序
     */
    public void testSort1() {
        List<Integer> integerList = new ArrayList<Integer>();
        // 插入十个100以内的不重复随机整数
        Random random = new Random();
        Integer k;
        for (int i = 0; i < 10; i++) {
            do {
                k = random.nextInt(100);
            } while (integerList.contains(k));
            integerList.add(k);
            System.out.println("成功添加整数:" + k);
        }
        System.out.println("-------------排序前--------------");
        for (Integer integer : integerList) {
            System.out.println("元素:" + integer);
        }
        Collections.sort(integerList);
        System.out.println("----------------排序后-------------------");
        for (Integer integer : integerList) {
            System.out.println("元素:" + integer);
        }
    }


    /**
     * 2 对String泛型的List进行排序
     * 创建String泛型的List,添加三个乱序的String元素
     * 调用sort方法,再次输出排序后的顺序
     */
    public void testSort2() {
        List<String> stringList = new ArrayList<String>();
        stringList.add("microsoft");
        stringList.add("google");
        stringList.add("lenovo");
        System.out.println("------------排序前-------------");
        for (String string : stringList) {
            System.out.println("元素:" + string);
        }
        Collections.sort(stringList);
        System.out.println("--------------排序后---------------");
        for (String string : stringList) {
            System.out.println("元素:" + string);
        }
    }


    /**
     * 3 对其他类型泛型的List进行排序,以Student为例。
     */
    public void testSort3() {
        List<Student> studentList = new ArrayList<Student>();
        Random random = new Random();
        studentList.add(new Student(random.nextInt(1000) + "", "Mike"));
        studentList.add(new Student(random.nextInt(1000) + "", "Angela"));
        studentList.add(new Student(random.nextInt(1000) + "", "Lucy"));
        studentList.add(new Student(10000 + "", "Beyonce"));  // 按字符串排序规则排序
        System.out.println("--------------排序前---------------");
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + ":" + student.name);
        }
        Collections.sort(studentList);
        System.out.println("----------------排序后------------------");
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + ":" + student.name);
        }
        Collections.sort(studentList, new StudentComparator());
        System.out.println("----------------按照姓名排序后-----------------");
        for (Student student : studentList) {
            System.out.println("学生:" + student.id + ":" + student.name);
        }
    }


    /**
     * @param args
     */
    public static void main( String[] args ) {
        CollectionsTest ct = new CollectionsTest();
        ct.testSort1();
        ct.testSort2();
        ct.testSort3();
    }


}

四 结果

成功添加整数:48
成功添加整数:92
成功添加整数:28
成功添加整数:53
成功添加整数:74
成功添加整数:60
成功添加整数:41
成功添加整数:91
成功添加整数:66
成功添加整数:65
-------------排序前--------------
元素:48
元素:92
元素:28
元素:53
元素:74
元素:60
元素:41
元素:91
元素:66
元素:65
----------------排序后-------------------
元素:28
元素:41
元素:48
元素:53
元素:60
元素:65
元素:66
元素:74
元素:91
元素:92
------------排序前-------------
元素:microsoft
元素:google
元素:lenovo
--------------排序后---------------
元素:google
元素:lenovo
元素:microsoft
--------------排序前---------------
学生:413:Mike
学生:554:Angela
学生:923:Lucy
学生:10000:Beyonce
----------------排序后------------------
学生:10000:Beyonce
学生:413:Mike
学生:554:Angela
学生:923:Lucy
----------------按照姓名排序后-----------------
学生:554:Angela
学生:10000:Beyonce
学生:923:Lucy
学生:413:Mike


Process finished with exit code 0

五 多字段比较排序

1 需求

对工人进行排序:首先按工资有由低到高排序(升序),当工资相同则按年龄由高到底排序(降序)。

2 实现

package Comparable;

import java.util.Arrays;
import java.util.Collections;

/**
 * Copyright (C), 2020-2020, XXX有限公司
 * FileName: Worker
 * Author:   cakin
 * Date:     2020/3/19 10:26
 * Description: 工人类
 */
public class Worker implements Comparable<Worker> {
    private String name;
    private int age;
    private int salary;

    public Worker( String name, int age, int salary ) {
        super();
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public int getSalary() {
        return salary;
    }

    /**
     * 实现Comparable接口的compareTo方法,在此方法中定义自己的比较规则 首先按工资有由低到高排序,当工资相同则按年龄由高到底排序
     */
    @Override
    public int compareTo( Worker other ) {
        // TODO Auto-generated method stub
        if (this.salary < other.getSalary()) { // 工资小于其他人时返回负值
            return -1;
        } else if (this.salary > other.getSalary()) { // 工资大于其他人时返回正值
            return 1;
        } else { // 工资等于其他人时按照年龄再排序
            if (this.age < other.getAge()) {
                return 1;// 表示由高到低排序
            } else if (this.age >= other.getAge()) {
                return -1;
            }
        }
        return 0;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return this.name + "\t" + this.age + "\t" + this.salary;
    }


    public static void main( String[] args ) {
        // TODO Auto-generated method stub

        Worker[] workers = new Worker[5];
        workers[0] = new Worker("test1", 25, 2000);
        workers[1] = new Worker("test2", 24, 2100);
        workers[2] = new Worker("test3", 26, 2100);
        workers[3] = new Worker("test4", 27, 2200);
        workers[4] = new Worker("test5", 28, 1900);

        //调用Arrays.sort()方法进行排序
        Collections.sort(Arrays.asList(workers));
        for (Worker w : workers) {
            System.out.println(w);
        }
    }
}

3 测试

test5	28	1900
test1	25	2000
test3	26	2100
test2	24	2100
test4	27	2200

实现了先按照工资升序,工资相同的,再按照年龄降序。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值