• java Comparable and Comparator


    1.Comparable简介

    此接口对实现它的每个类的对象强加一个总排序。这种排序被称为类的自然排序,类的compareTo方法被称为其自然比较方法。可以通过

    Collections.sort(和Arrays.sort)自动对实现此接口的对象的列表(和数组)进行排序。实现此接口的对象可用作有序映射中的键或有序

    集中的元素,而无需指定比较器。

    注:若一个类实现了该接口,说明该类本身是支持排序的。在java中倡导所有实现Comparable接口的类都应该保持与

    equals()一致的排序顺序,因此还需要重写equals方法和hashcode方法。

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

    2.Comparable定义

    实现Comparable接口仅需实现compareTo方法。

    通过x.compareTo(y)来比较x与y的大小:1)返回负数,说明x小于y;2)返回0,说明x与y相等;3)返回正数,说明x大于y。

    1 package java.lang;
    2 import java.util.*;
    3 
    4 public interface Comparable<T> {
    5     public int compareTo(T o);
    6 }

    3.Comparator简介

    该接口内部是一个比较函数,它对某些对象集合施加总排序。可以将比较器传递给排序方法(例如Collections.sort或Arrays.sort),以便

    精确控制排序顺序。比较器还可用于控制某些数据结构的顺序(例如有序集或有序映射),或者为不具有自然顺序的对象集合提供排序。

    注:若一个类没有实现Comparable接口,则该类自身无法排序;此时可以使用Comparator帮助这个类进行排序。

    A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

    4. Comparator定义

    1 package java.util;
    2 
    3 public interface Comparator<T> {
    4 
    5     int compare(T o1, T o2);
    6 
    7     boolean equals(Object obj);
    8 }

     5. 示例

    5.1 Customer.java

    该类实现了Comparable接口,即该类的成员对象自身是支持排序的。

     1 import java.util.Objects;
     2 
     3 public class Customer implements Comparable<Customer>{
     4 
     5     private int customerId;
     6     private String customerName;
     7 
     8     public Customer(Integer customerId, String customerName) {
     9         this.customerId = customerId;
    10         this.customerName = customerName;
    11     }
    12 
    13     public int getCustomerId() {
    14         return customerId;
    15     }
    16     public String getCustomerName() {
    17         return customerName;
    18     }
    19 
    20     @Override
    21     public String toString() {
    22         return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
    23     }
    24 
    25      /*
    26      * 重写compareTo方法
    27      * 按Id或者name排序
    28      * 可以对整体添加负号决定升降序
    29      * */
    30     @Override
    31     public int compareTo(Customer o) {
    32 //        return this.customerId - o.customerId;
    33         return this.customerName.compareTo(o.customerName);
    34     }
    35 
    36     /*
    37     * 重写equals和hashcode方法
    38     * 这里id和name相同则为同一对象
    39     * */
    40     @Override
    41     public boolean equals(Object o) {
    42         if (this == o) return true;
    43         if (!(o instanceof Customer)) return false;
    44         Customer customer = (Customer) o;
    45         return customerId == customer.customerId &&
    46                 Objects.equals(customerName, customer.customerName);
    47     }
    48 
    49     @Override
    50     public int hashCode() {
    51         return Objects.hash(customerId, customerName);
    52     }
    53 
    54 }
    View Code

    5.2 CustomerComparator.java

    该类实现了Comparator接口,帮助Customer对象按Id排序。

     1 import java.util.Comparator;
     2 
     3 public class CustomerComparator implements Comparator<Customer> {
     4 
     5     @Override
     6     public int compare(Customer c1, Customer c2) {
     7         // 按Id排序
     8         return c1.getCustomerId() - c2.getCustomerId();
     9      }
    10 }

    5.3 SortFunc.java

    使用两种接口的排序方法对list进行排序。

     1 import java.util.*;
     2 
     3 public class SortFunc {
     4     public static void main(String[] args){
     5         List<Customer> list = new ArrayList<>();
     6         list.add(new Customer(1, "A"));
     7         list.add(new Customer(2, "C"));
     8         list.add(new Customer(3, "D"));
     9         list.add(new Customer(4, "B"));
    10 
    11         // 原始排序
    12         System.out.println("原始的排序:"+list);
    13 
    14         // 使用compare接口按name排序
    15         Collections.sort(list);
    16         System.out.println("使用compare接口按name排序:"+list);
    17 
    18         // 使用comparator接口按id排序
    19 //        Collections.sort(list, new CustomerComparator());     // 两个方式
    20         list.sort(new CustomerComparator());
    21         System.out.println("使用comparator接口按id排序:"+list);
    22 
    23         // 判断c1和c2是否引用同一个对象;判断c1和c2是否等价
    24         Customer c1 = new Customer(6,"c1");
    25         Customer c2 = new Customer(6,"c1");
    26         System.out.println(c1==c2);
    27         System.out.println(c1.equals(c2));
    28     }
    29 }

    显示结果如下所示,附带==与equals的说明:

    对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价,即数据是否一致。

    1 原始的排序:[Customer:[Id=1, Name=A], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D], Customer:[Id=4, Name=B]]
    2 使用compare接口按name排序:[Customer:[Id=1, Name=A], Customer:[Id=4, Name=B], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D]]
    3 使用comparator接口按id排序:[Customer:[Id=1, Name=A], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D], Customer:[Id=4, Name=B]]
    4 false
    5 true

    !!!

  • 相关阅读:
    iOS 自定义UITabBarController的tabBar
    iOS 设置导航栏之二(设置导航栏的颜色、文字的颜色、左边按钮的文字及颜色)
    iOS 设置导航栏的颜色和导航栏上文字的颜色
    iOS 修改UITextField的placeholder属性的字体颜色(修改UITextField占位符字体的颜色)
    iOS TPKeyboardAvoiding自动识别键盘的高度
    iOS 获取快递物流信息(GCD异步加载)
    iOS 图片循环滚动(切片效果)
    iOS block在两个页面间的简单传值
    swift
    iOS 10 之后权限设置
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/10656433.html
Copyright © 2020-2023  润新知