天天看點

comparator接口與Comparable接口的差別

comparable & comparator 都是用來實作集合中元素的比較、排序的,隻是 comparable 是在集合内部定義的方法實作的排序,comparator 是在集合外部實作的排序,是以,如想實作排序,就需要在集合外定義 comparator 接口的方法或在集合内實作 comparable 接口的方法。

comparator位于包java.util下,而comparable位于包   java.lang下

comparable 是一個對象本身就已經支援自比較所需要實作的接口(如 string、integer 自己就可以完成比較大小操作,已經實作了comparable接口)   

自定義的類要在加入list容器中後能夠排序,可以實作comparable接口,在用collections類的sort方法排序時,如果不指定comparator,那麼就以自然順序排序,如api所說:

sorts the specified list into ascending order, according to the natural ordering of its elements. all elements in the list must implement the comparable interface

這裡的自然順序就是實作comparable接口設定的排序方式。

而 comparator 是一個專用的比較器,當這個對象不支援自比較或者自比較函數不能滿足你的要求時,你可以寫一個比較器來完成兩個對象之間大小的比較。

可以說一個是自已完成比較,一個是外部程式實作比較的差别而已。

用 comparator 是政策模式(strategy design pattern),就是不改變對象自身,而用一個政策對象(strategy object)來改變它的行為。

下一篇: Map小結