java.lang.Iterable接口 - 循环打印MAP容器时候所想到的

以前只做过LIST的循环打印,昨天被问到MAP循环怎么弄,一下给人问蒙了,最后查API,发现Map类中有一个方法values() ,可以返回一个Collection集合容器,然后可以循环打印。而且发现实现了Iterable的类都可以用foreach来循环打印,JDK5后的新特性。
虽然说,不用实现Iterable也可以循环抓出容器里的值,但是用用新特性也没坏处。准备从Iterable开始分析。

类名:java.lang Interface Iterable<T>
方法:Iterator<T> iterator()
说明:Implementing this interface allows an object to be the target of the "foreach" statement.

[b]All Known Subinterfaces: [/b]
BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, [b]Collection<E>, [/b]Deque<E>, DirectoryStream<T>, [b]List<E>, [/b]NavigableSet<E>, Queue<E>, [b]Set<E>, SortedSet<E>[/b]


[b]All Known Implementing Classes: [/b]
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, [b]ArrayList[/b], AttributeList, BatchUpdateException, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, DelayQueue, EnumSet, [b]HashSet[/b], JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, [b]LinkedHashSet[/b], [b]LinkedList[/b], Path, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, RowSetWarning, SecureDirectoryStream, SerialException, ServiceLoader, SQLClientInfoException, SQLDataException, SQLException, SQLFeatureNotSupportedException, SQLIntegrityConstraintViolationException, SQLInvalidAuthorizationSpecException, SQLNonTransientConnectionException, SQLNonTransientException, SQLRecoverableException, SQLSyntaxErrorException, SQLTimeoutException, SQLTransactionRollbackException, SQLTransientConnectionException, SQLTransientException, SQLWarning, Stack, SyncFactoryException, SynchronousQueue, SyncProviderException, [b]TreeSet[/b], Vector


自己写的一个类:

package test;

import java.util.Iterator;

public class IterableTest implements Iterator{

public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}

public Object next() {
// TODO Auto-generated method stub
return null;
}

public void remove() {
// TODO Auto-generated method stub

}

}



实现Iterable接口必须实现hasNext(),next(),remove三个方法。
实现的时候可以:

public class IterableTest implements Iterator<String>{
//下面的next()方法也有所改变
public String next() {
//但是不能
public class IterableTest implements Iterator<String>,Iterator<Integer>{

因为在实现方法后next方法有一个返回值,默认是Object,如果实现两个类型不一致的接口,那么就与“在一个类中写两个方法名和参数一致,而返回值不一致”的逻辑性错误一样了。


待续。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值