1. 程式人生 > >java.lang.Iterable介面

java.lang.Iterable介面

以前只做過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,如果實現兩個型別不一致的介面,那麼就與“在一個類中寫兩個方法名和引數一致,而返回值不一致”的邏輯性錯誤一樣了。


待續。。。