zoukankan      html  css  js  c++  java
  • Comparable与Comparator的区别

    一。比较

    Comparable & Comparator 都是用来实现集合中元素的比较、排序的,只是 Comparable 是在内部实现的排序,Comparator 是在外部实现的排序。

    用 Comparator 是策略模式(strategy design pattern),不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
      
    比如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要

    使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。

    二。介绍
    1.java.util.Comparator

        int compare(T o1, T o2) 

        boolean equals(Object obj) 

      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.

    public static <T> void sort(List<T> list,
                                Comparator<? super T> c)

    2.java.lang.Comparable

        int compareTo(T o) 

      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.



  • 相关阅读:
    堆排序
    如何在.Net中使用MongoDB
    二叉树遍历 C#
    对C# 中Readonly的再认识
    对C# 构造函数的理解
    TypeScript学习: 九、TypeScript的泛型
    TypeScript学习: 八、TypeScript的属性接口用法封装ajax
    锚点跳转不改变History
    设计模式笔记—代理模式
    小程序开发二:上手第一个小程序
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3835453.html
Copyright © 2011-2022 走看看