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.

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


All Known Implementing Classes:
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BatchUpdateException, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, 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, TreeSet, 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,如果实现两个类型不一致的接口,那么就与“在一个类中写两个方法名和参数一致,而返回值不一致”的逻辑性错误一样了。


待续。。。

你可能感兴趣的:(java)