Java集合中Comparable和Comparator辨析

轉載自:http://blog.csdn.net/longshengguoji/article/details/41598741

一.Comparable和Comparator簡介

在對集合元素進行比較時一般使用TreeSet.對於簡單的數據類型,TreeSet可以直接進行比較。但是對於複雜的數據類型,比如自己定義的數據類型或者類,就需要自己設置比較方法與比較規則了,這時就需要使用Comparable和Comparator。 Comparable和Comparator都是用來實現集合中的排序的,只是Comparable是在集合內部定義的方法實現排序,而Comparator是在集合外部實現的排序。所以如果想對結合排序,需要在集合外定義Comparator接口的方法或在集合內部實現Comparable接口的方法。
一個類實現了Comparable接口則表明這個類的對象之間是可以相互比較的,這個類對象組成的結合就可以直接使用sort方法排序。
Comparator是策略模式,就是在不改變對象自身,而用一種策略對象來改變它的行爲,將算法和數據分離,Comparator還可以在下面兩種環境下使用:
1.類在設計時沒有考慮到比較問題而沒有實現Comparable接口,則可以通過Comparator來實現排序而不必修改原來的類代碼。
2.類設計時實現了Comparable接口,但是後面的使用者卻想用一種新的比較規則對類進行比較

二. 用法示例

Comparable排序:
首先定義實現Comparable接口的Item類

package com.collection;
import java.util.Objects;

/**
 * 定義實現Comparable接口的Item類
 *
 */
public class Item implements Comparable<Item>{
    private String description;
    private int partNumber;

    public Item(String aDescription, int aPartNumber)
    {
       description = aDescription;
       partNumber = aPartNumber;
    }

    public String getDescription()
    {
       return description;
    }

    public String toString()
    {
       return "[description="+description+",partNumber="+partNumber+"]";
    }

    public boolean equals(Object otherObject)
    {
       if(this == otherObject)
           return true;
       if(otherObject == null)
           return false;
       if(getClass()!=otherObject.getClass())
           return false;
       Item other = (Item)otherObject;
       return Objects.equals(description, other.description) &&partNumber == other.partNumber;
    }

    public int hashCode()
    {
       return Objects.hash(description,partNumber);
    }

    //重載compareTo方法,設定Item對象的比較方法
    @Override
    public int compareTo(Item other)
    {

       return Integer.compare(partNumber, other.partNumber);      
    }
}

定義對Item進行排序的類,對集合進行排序是使用TreeSet或TreeMap,此處用TreeSet存放集合元素。

package com.collection;
import java.util.TreeSet;
public class ListSortWithComparable
{
    public static void main(String[] args)
    {
       TreeSet<Item> set = new TreeSet<>();
       set.add(new Item("zhuwei",26));
       set.add(new Item("yinyuchun",24));
       set.add(new Item("xiaobai",25));
       set.add(new Item("chun",24));
       for(Item it : set)
       {
           System.out.println(it.toString());
       }
    }
}

Comparator排序實現示例:
首先定義需要排序的類People

package com.collection;

public class People
{
    private String name;
    public String getName()
    {
       return name;
    }
    public void setName(String name)
    {
       this.name = name;
    }
    public int getAge()
    {
       return age;
    }
    public void setAge(int age)
    {
       this.age = age;
    }
    private int age;

    public People(String name,int age)
    {
       this.name = name;
       this.age = age;
    }
    public String toString()
    {
       return ("name:"+this.name+",age:"+this.age);
    }
}

接着建立對People進行排序的類,利用Comparator進行排序有兩種方法,第一種方法是把需要排序的People對象放在List集合中,然後調用Collection.sort(list,comparator)方法進行排序;第二中排序方法是直接把Comparator對象傳遞給TreeSet的構造器,並重載Comparator類的compara方法,指定排序規則,這種方法不需要讓People類實現Comparator接口,且其代碼較簡潔。

Comparator

package com.collection; 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class ListSortWithComparator
{  
    publicstatic void main(String[] args)
    {
       /*
        * 使用comparator進行排序的第一種方法,
        * 定義一個實現Comparator接口的類,並重載compara方法,設定比較規則
        * 利用Collection.sort(list,comparator)方法實現排序,
        * Collection.sort(list,comparator)方法的第一個參數爲List類型,因此要排序的元素需要放在List集合中
        */
       List<People>list = new ArrayList<>();
       list.add(newPeople("zhuwei",26));
       list.add(newPeople("yinyuchun",25));
       list.add(newPeople("xiaobai",26));

       MComparatorcomparator = new MComparator();

       Collections.sort(list,comparator);

       for(Peoplep:list)
       {
           System.out.println(p.toString());
       }


       /*
        * 使用comparator進行排序的第二種方法,
         * 該方法不需要People實現Comparator接口
        * 直接Comparator對象傳遞給TreeSet的構造器,
        * 並重載Comparator類的compara方法,指定排序規則
        */
//     SortedSet<People>set = new TreeSet<>(
//            newComparator<People>()
//            {
//
//                //重載Comparator類的compara方法,設定比較規則:按名字降序排列
//                @Override
//                publicint compare(People people1, People people2)
//                {
//                   //TODO Auto-generated method stub
//                   if(people1.getName().compareTo(people2.getName())>0)
//                   {
//                       return-1;
//                   }
//                   else
//                   {
//                       return1;
//                   }
//                  
//                }
//               
//            }
//            );
//     set.addAll(list);
//     System.out.println("輸出按降序排列的結果:");
//     for(Peoplep: set)
//     {
//         System.out.println(p.toString());
//     }
    }
}
發佈了160 篇原創文章 · 獲贊 48 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章