Java iterator iterable comparable comparator等接口設計的區別

java.lang

Interface Iterable<T>

Iterator<T> iterator()
Returns an iterator over a set of elements of type T.


Iterable接口只有一個方法,並返回一個迭代器。很多集合類都實現了該接口,比如Collection  Map  Queue等等

java.util

Interface Iterator<E>

boolean hasNext()   //Returns true if the iteration has more elements.

E next()   //Returns the next element in the iteration.

void remove()  //Removes from the underlying collection the last element returned by this iterator (optional operation).

而iterator迭代器來說,有next  hasnext  remove方法

因爲Iterator接口的核心方法next()或者hasNext() 是依賴於迭代器的當前迭代位置的。 如果Collection直接實現Iterator接口,勢必導致集合對象中包含當前迭代位置的數據(指針)。 當集合在不同方法間被傳遞時,由於當前迭代位置不可預置,那麼next()方法的結果會變成不可預知。 除非再爲Iterator接口添加一個reset()方法,用來重置當前迭代位置。 但即時這樣,Collection也只能同時存在一個當前迭代位置。 而Iterable則不然,每次調用都會返回一個從頭開始計數的迭代器。 多個迭代器是互不干擾的。 

java.lang

Interface Comparable<T>

int compareTo(T o)   //Compares this object with the specified object for order.

若一個類實現了Comparable接口,就意味着“該類支持排序”。  即然實現Comparable接口的類支持排序,假設現在存在“實現Comparable接口的類的對象的List列表(或數組)”,則該List列表(或數組)可以通過 Collections.sort(或 Arrays.sort)進行排序。


java.util

Interface Comparator<T>


int compare(T o1, T o2)   //Compares its two arguments for order.

boolean equals(Object obj)  //Indicates whether some other object is "equal to" this comparator.
Comparator 是比較器接口我們若需要控制某個類的次序,而該類本身不支持排序(即沒有實現Comparable接口);那麼,我們可以建立一個“該類的比較器”來進行排序。這個“比較器”只需要實現Comparator接口即可。


Comparable 與 Comparator比較

Comparable是排序接口;若一個類實現了Comparable接口,就意味着“該類支持排序”。
而Comparator是比較器;我們若需要控制某個類的次序,可以建立一個“該類的比較器”來進行排序。
我們不難發現:Comparable相當於“內部比較器”,而Comparator相當於“外部比較器”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章