Comparator and Comparable及Collections and Collection的用法和区别

  此篇博客整理自网络

  

  Collections and Collection

  Collection是一个集合接口,Collections是一个包装类(或帮助类),这是二者最明显的区别。Collections提供了一 些static方法来对 Collection对象进行处理,比如:对Collection对象的复制、添加元素、修改元素、对元素进行排序、交换俩个元素的位置、取 Collection的子集等等操作。另外Collection是j2sdk中集合框架的根接口,所有的其他特殊类型的结合接口或者类都直接或间接的实现 了这个接口。

  java.util.Collections   API >>

 1 public interface Collection<E> extends Iterable<E> {
 2     int size();
 3     boolean isEmpty();
 4     boolean contains(Object o);
 5     Iterator<E> iterator();
 6     Object[] toArray();
 7     <T> T[] toArray(T[] a);
 8     boolean add(E e);
 9     boolean remove(Object o);
10     boolean containsAll(Collection<?> c);
11     boolean addAll(Collection<? extends E> c);
12     boolean removeAll(Collection<?> c);
13     boolean retainAll(Collection<?> c);
14     void clear();
15     boolean equals(Object o);
16     int hashCode();
17 }
  java.util.Collections   API >>

1 public class Collections {
2   //注意Collections只是Collection集合接口的一个帮助类,并没有implements Collection  
3   ... ...  
4 }

  Comparator and Comparable 

  Comparator和Comparable都是接口,俩者之间可以说没什么关系。Comarator位于包java.util下,而Comparable位于包 java.lang下。通俗的说:Comparator是一个比较器,相当于一种工具,它定义了俩个方法,分别是 int compare(T o1, T o2)和 boolean (Object obj),所以你可以通过实现这个接口来定义你所有需要的比较器,如比较俩个人的大小,对象人有姓名、性别、年龄等属性,你在定义这个比较器的时候就可以在compare方法中对传入的俩个参数(person1,person2)的年龄进行大小的比较,从而确定这俩个人的大小。
  Comparable接口是你要是定义的类要实现的一个接口(如果这个类的实例需要和同一类的别的实例比较大小,而这个大小关系你希望是你自己定义的),它只提供了 int compareTo(T o)方法,也就是说假如我定义了一个Person类,这个类实现了 Comparable接口,那么当我实例化Person类的person1后,我想比较person1和一个现有的Person对象person2的大小时,我就可以这样来调用:person1.comparTo(person2),通过返回值就可以判断了;而此时如果你定义了一个 PersonComparator(实现了Comparator接口)的话,那你就可以这样:PersonComparator comparator= new PersonComparator();comparator.compare(person1,person2);。

  java.lang.Comparable API >>

1 public interface Comparable<T> {
2     public int compareTo(T o);
3 }
    此接口强行对实现它的每个类的对象进行整体排序。此排序被称为该类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
  实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射表中的键或有序集
合中的元素,无需指定比较器。


 java.util.Comparator API >>

1 public interface Comparator<T> {
2     int compare(T o1, T o2);
3     boolean equals(Object obj);
4 }

   比较函数强行对某些对象 collection 进行整体排序。可以将 Comparator 传递给 sort 方法(如 Collections.sort),从而允许在排序顺序上实现精确控制。还可以使用 Comparator 来控制某些数据结构(如 TreeSet 或 TreeMap)的顺序。

  当需要排序的集合或数组不是单纯的数字类型的时候,通常可以使用Comparator或Comparable,以简单的方式实现对象排序或自定义排序。

  Comparator和Comparable的区别如下:

Comparable用在对象本身,说明这个对象是可以被比较的,也就是说可以被排序的。String和Integer之所以可以比较大小,是因为它们都实现了Comparable接口,并实现了compareTo()方法)。

Comparator用在对象外面,相当于定义了一套排序算法来排序。

  
   java.lang.String  API >>


 

 1 public final class String implements java.io.Serializable, Comparable<String>, CharSequence{
    ... ...
    //String和Integer之所以可以比较大小,是因为它们都实现了Comparable接口,并实现了compareTo()方法
2 public int compareTo(String anotherString) { 3 int len1 = count; 4 int len2 = anotherString.count; 5 int n = Math.min(len1, len2); 6 char v1[] = value; 7 char v2[] = anotherString.value; 8 int i = offset; 9 int j = anotherString.offset; 10 11 if (i == j) { 12 int k = i; 13 int lim = n + i; 14 while (k < lim) { 15 char c1 = v1[k]; 16 char c2 = v2[k]; 17 if (c1 != c2) { 18 return c1 - c2; 19 } 20 k++; 21 } 22 } else { 23 while (n-- != 0) { 24 char c1 = v1[i++]; 25 char c2 = v2[j++]; 26 if (c1 != c2) { 27 return c1 - c2; 28 } 29 } 30 } 31 return len1 - len2; 32 } 33 }

  下面通过具体的例子来理解Comparator和Comparable的区别:

   Comparator实例如下:

 1 class Name implements Comparable<Name>{  
 2     public String firstName,lastName;  
 3     public Name(String firstName,String lastName){  
 4         this.firstName=firstName;  
 5         this.lastName=lastName;  
 6     }  
 7     //实现接口 
 8     public int compareTo(Name o) {           
 9         int lastCmp=lastName.compareTo(o.lastName);  
10         return (lastCmp!=0?lastCmp:firstName.compareTo(o.firstName));  
11     }    
12     //便于输出测试  
13     public String toString(){                
14         return firstName+" "+lastName;  
15     }  
16 } 
 1 public class NameSort {  
 2      public static void main(String[] args) {  
 3          Name nameArray[] = {  
 4             new Name("John", "Lennon"),  
 5             new Name("Karl", "Marx"),  
 6             new Name("Groucho", "Marx"),  
 7             new Name("Oscar", "Grouch")  
 8         }; 
 9         Arrays.sort(nameArray);  
10         System.out.println(Arrays.toString(nameArray));;  
11     }  
12 } 

  运行结果:[Oscar Grouch, John Lennon, Groucho Marx, Karl Marx]
  Comparable实例如下:

 1 public  class  User implements  Comparable<Object> {  
 2     private  String id;  
 3     private  int  age;  
 4   
 5     public  User(String id, int  age) {  
 6         this .id = id;  
 7         this .age = age;  
 8     }  
 9   
10     public  int  getAge() {  
11         return  age;  
12     }  
13     public  void  setAge(int  age) {  
14         this .age = age;  
15     }  
16     public  String getId() {  
17         return  id;  
18     }  
19     public  void  setId(String id) {  
20         this .id = id;  
21     }  
22     
23     public int compareTo(Object o) {
24         return this.age-((User)o).getAge();
25     }
26   
27     /**  
28      * 测试方法  
29      */   
30     public static void main(String[] args){  
31         User[] users = new User[]{new User("a", 30),new User("b", 20 )};  
32         Arrays.sort(users);  
33         for  (int  i = 0 ; i < users.length; i++) {  
34             User user = users[i];  
35             System.out.println(user.getId() + " "  + user.getAge());  
36         }  
37     }  
38 }

  运行结果:b 20
       a 30

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/gw811/p/2677212.html