增強for循環
只適合取數據,只能用在數組、或實現Iterable接口的集合類上。
List,Set,Map
List
`
public interface List<E>
extends Collection<E>
`
實現的類:AbstractList , AbstractSequentialList , ArrayList , AttributeList , CopyOnWriteArrayList , LinkedList , RoleList , RoleUnresolvedList , Stack , Vector
查看Collection接口
`
public interface Collection<E> extends Iterable<E>
`
子接口:BeanContext , BeanContextServices , BlockingDeque
所有已實現類:AbstractCollection , AbstractList , AbstractQueue , AbstractSequentialList , AbstractSet , ArrayBlockingQueue , ArrayDeque , ArrayList , AttributeList , BeanContextServicesSupport , BeanContextSupport , ConcurrentHashMap.KeySetView , ConcurrentLinkedDeque , ConcurrentLinkedQueue , ConcurrentSkipListSet , CopyOnWriteArrayList , CopyOnWriteArraySet , DelayQueue , EnumSet , HashSet , JobStateReasons , LinkedBlockingDeque , LinkedBlockingQueue , LinkedHashSet , LinkedList , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , RoleList , RoleUnresolvedList , Stack , SynchronousQueue , TreeSet , Vector
查看Iterable接口
`
public interface Iterable<T>
`
子接口:BeanContext , BeanContextServices , BlockingDeque
所有已實現的類:AbstractCollection , AbstractList , AbstractQueue , AbstractSequentialList , AbstractSet , ArrayBlockingQueue , ArrayDeque , ArrayList , AttributeList , BatchUpdateException , BeanContextServicesSupport , BeanContextSupport , ConcurrentHashMap.KeySetView , ConcurrentLinkedDeque , ConcurrentLinkedQueue , ConcurrentSkipListSet , CopyOnWriteArrayList , CopyOnWriteArraySet , DataTruncation , DelayQueue , EnumSet , HashSet , JobStateReasons , LinkedBlockingDeque , LinkedBlockingQueue , LinkedHashSet , LinkedList , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , RoleList , RoleUnresolvedList , RowSetWarning , SerialException , ServiceLoader , SQLClientInfoException , SQLDataException , SQLException , SQLFeatureNotSupportedException , SQLIntegrityConstraintViolationException , SQLInvalidAuthorizationSpecException , SQLNonTransientConnectionException , SQLNonTransientException , SQLRecoverableException , SQLSyntaxErrorException , SQLTimeoutException , SQLTransactionRollbackException , SQLTransientConnectionException , SQLTransientException , SQLWarning , Stack , SyncFactoryException , SynchronousQueue , SyncProviderException , TreeSet , Vector
實現了這個接口的集合對象支持叠代,是可叠代的。
https://www.cnblogs.com/keyi/p/5821285.html
一個集合對象要表明自己支持叠代,能有使用foreach語句的特權,就必須實現Iterable接口,表明我是可叠代的!然而實現Iterable接口,就必需為foreach語句提供一個叠代器。
這個叠代器是用接口定義的 iterator方法提供的。也就是iterator方法需要返回一個Iterator對象。
Iterator接口
查看ArrayList裏面的iterator()源碼:
`
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
`
自定義StringList
`
public class StringList<E> implements Iterable<E>{
private int size;
transient Object[] elementData;
private static final Object[] EMPTY_ELEMENTDATA = {};
public StringList(Collection<? extends E> c){
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
public Iterator<E> iterator() {
return new StringList.Itr();
}
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public E next() {
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = StringList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}
}
`
`
public class TestStringList {
public static void main(String[] args) {
List<String>list=new ArrayList<String>();
list.add("AAAA");
list.add("BBBB");
list.add("CCCC");
StringList<String> stringList=new StringList<String>(list);
for (String str:stringList){
System.out.println(str);
}
}
}
`
結果:
增強for循環