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相当于“外部比较器”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值