美文网首页
实现 Comparable 接口完成排序

实现 Comparable 接口完成排序

作者: MikeShine | 来源:发表于2022-01-10 16:39 被阅读0次

1. 写在前面

之前看了一下实现 Iterable 接口,自己手写了一个 ReverseList 集合类,最终可以反向遍历这个 集合类。
然后就让我想到了 Comparable 接口,这里看一下如何通过实现,从而完成排序。


2. Comparable 接口实现

一些基本的类型,可以直接调用 Arrays.sort() / Collections.sort() 来完成,但是对于自己写的一些类,编译器实际上是不知道根据什么规则来对其排序的。
因此,如果自己的类需要直接进行排序,则需要告诉编译器如何进行排序。

这里有两种实现方式:

  • 类和排序放在一起,即类实现Comparable 接口
  • 类和排序分开,即重新编写一个 xxxComparator 来实现 Comparator 接口

直接上代码,这里完成一个对 Student 类 的排序,分别使用两种方法。

/**
 * 实现了 Comparable 的 Student 类
 * @author mikeshine
 */
@Data
public class Student implements Comparable<Student>{

    private Integer age;
    private String name;
    private Double height;

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

    /**
     * 这里是需要重写的 compareTo() 方法
     * 这个方法规定比较的规则
     * @param student
     * @return
     */
    @Override
    public int compareTo(Student student) {
        return (int)(this.age - student.getAge());
    }
}

/**
 * 实现了 Comparator 的 Student 比较器
 * @author mikeshine
 * @date 2022-01-10
 */
public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return (int)(o1.getHeight()-o2.getHeight());
    }
}

两种方式在调用时候有一些区别,后者需要作为参数传入,前者直接调用即可。

 public static void main(String[] args) {
        Student ming = new Student(12,"ming",168.00);
        Student hong = new Student(13,"hong",167.00);
        Student xing = new Student(14,"xing",165.00);
        List<Student> students = new ArrayList<>(Arrays.asList(ming,hong,xing));
        // 按照Student类中的规则,即按照age 的升序
        Collections.sort(students);
        // 按照StudentComparator 类中的规则,即按照 height 的升序
        Collections.sort(students, new StudentComparator());
    }

除了上述两种调用方式之外,更为常用的用法是通过 stream().sorted()方法来调用,这种调用方式对于后者的实现更加便捷,通过 lambda 表达式即可实现。
代码如下

 public static void main(String[] args) {
        Student ming = new Student(12,"ming",168.00);
        Student hong = new Student(13,"hong",167.00);
        Student xing = new Student(14,"xing",165.00);
        List<Student> students = new ArrayList<>(Arrays.asList(ming,hong,xing));
        // 通过 Student 类中的规则
        List<Student> sortedStudents = students.stream().sorted(Comparator.comparing(Student::getHeight)).collect(Collectors.toList());
        // 通过自己编写的规则,height 升序
        List<Student> defaultSortedStudents = students.stream().sorted((t1,t2)-> (int)(t1.getHeight()- t2.getHeight())).collect(Collectors.toList());;
    }

3. 重写 equals() & hasCode() 方法

为什么把这一部分放到这里来看呢,因为事实上 equals() 也是一种比较,不过只是来比较是否相等,并不比较大小。

3.1 为什么要重写 equals() 方法

同上面说的重写 comparator() 方法 一样,你自己写的类,也需要知道如何判断 equals()相等与否,我们需要告诉编译器一种标准。
一般来说,重写 equals() 方法按照如下的步骤进行:

  • 对于 null,返回 false
  • 对于 非本类,返回 false
  • 对于 自身,返回 true
  • 写比较标准
/**
 * 重写 equals & hashCode 的类
 * @author mikeshine
 * @date 2021-01-10
 */
@Data
public class Employee {

    private int id;
    private String firstName;
    private String lastName;
    private String department;

    /**
     * 这里需要规定一下该类的 equals 方法的具体比较规则
     * @param obj
     * @return
     */
    @Override
    public boolean equals(Object obj) {
        if(obj==null){
            return false;
        }
        if(!(obj instanceof Employee)){
            return false;
        }
        if(this == obj){
            return true;
        }
        Employee employee = (Employee)obj;
        return (this.getId().equals(employee.getId()));
    }
}

3.2 为什么要写 hashCode() 方法

貌似只要有 equals() 方法就行了,但是看下面一个 case

        Employee em1 = new Employee();
        Employee em2 = new Employee();

        em1.setId(100);
        em2.setId(100);
        System.out.println(em1.equals(em2));

        Set set = new HashSet<>();
        set.add(em1);
        set.add(em2);
        System.out.println(set);

那么可以看到,这里的 haseSet 中,是有两个元素的,但是这两个元素其实是 equal 的,即一个对象
问题原因
java 中有如下的要求:

  • equals 的对象, hash 值必须相同
  • hash 相同的时候,equals 不必为 true。 hash碰撞 的 case

为什么有这样奇怪的要求
事实上,这样是为了快速判断对象是否相同。

// hashMap 中插入时做的判断
if (p.hash == hash &&
               ((k = p.key) == key || (key != null && key.equals(k))))

从上面来看,这里判断首先判断插入对象和已有对象的 hashCode是否相等,如果相等,则再去看 对象是否 equals;如果不想等,则直接结束判断。

因为 equals 的对象,hash 值一定是相同的。

回头看上面的例子,正是因为没有写 hashCod() 方法,因此两个 Employee 对象的 hash 值不同,所以就和插入进去了。

如何重写 hashCode()

这里其实没有一种标准的写法,其核心诉求是,返回与变量相关的 独一无二 的 hash 值。
这里看一个case。通用的写法是,根据一些经典的素数来搞。变量是 String等包装类,则直接掉用其本身的 hash(),否则直接将该变量加入。

@override
public int hashCode(){
      // 先定义一个 hash 值
      int hash = 17;
      // 根据比较变量(用在equals 中的)加入hash值
      hash = hash * 31 + getId();
      hash = hash * 31 + getName.hash();
      return hash;
}

相关文章

网友评论

      本文标题:实现 Comparable 接口完成排序

      本文链接:https://www.haomeiwen.com/subject/edmmcrtx.html