Java Iterator接口实现代码解析
Iterator接口
源代码
packagejava.util; importjava.util.function.Consumer; /** *Aniteratoroveracollection.{@codeIterator}takestheplaceof *{@linkEnumeration}intheJavaCollectionsFramework.Iterators *differfromenumerationsintwoways: * *
-
*
- Iteratorsallowthecallertoremoveelementsfromthe *underlyingcollectionduringtheiterationwithwell-defined *semantics. *
- Methodnameshavebeenimproved. *
Thisinterfaceisamemberofthe
* Thedefaultimplementationbehavesasif:
* 阅读笔记 1.Iterator接口与Enumeration接口的关系/Iterator接口在Java集合库中的作用 Iterator接口是Java集合框架的一部分,被用于替代原有的Enumeration接口。(“Iterator”比“Enumeration”更简短、表意更清晰、功能更多,具体的信息下面Enumeration接口的注解中说的挺清楚,且Enumeration注解中也建议编程人员改用Iterator接口) Java类库中,集合类的基本接口是Collection接口,而Collection接口实现了Iterable接口,Iterable接口中有一个iterator()方法用于获取Iterator对象。
*Forexample,toprintallelementsofaVector<E>v:
*
*Methodsareprovidedtoenumeratethroughtheelementsofa
*vector,thekeysofahashtable,andthevaluesinahashtable.
*Enumerationsarealsousedtospecifytheinputstreamstoa
*
*NOTE:ThefunctionalityofthisinterfaceisduplicatedbytheIterator
*interface.Inaddition,Iteratoraddsanoptionalremoveoperation,and
*hasshortermethodnames.Newimplementationsshouldconsiderusing
*IteratorinpreferencetoEnumeration.
*
*@seejava.util.Iterator
*@seejava.io.SequenceInputStream
*@seejava.util.Enumeration#nextElement()
*@seejava.util.Hashtable
*@seejava.util.Hashtable#elements()
*@seejava.util.Hashtable#keys()
*@seejava.util.Vector
*@seejava.util.Vector#elements()
*
*@authorLeeBoynton
*@sinceJDK1.0
*/
publicinterfaceEnumeration 2.hasNext()、next()、remove()方法的关系 hasNext()方法:判断是否还有元素可以进行迭代; next()方法:迭代元素; remove()方法: 三者关系:调用remove()方法前必须先调用next()方法,调用next()方法前最好先调用hasNext()方法。 3.具体实现类 AbstractList类中定义了一个实现了Iterator接口的内部类: 看完上面的代码,我对modCount、expectedModCount变量以及checkForComodification()方法的作用比较好奇,所以尝试着去搞清楚。 先来看modeCount变量,这个变量被声明在内部类的外部: Thisfieldisusedbytheiteratorandlistiteratorimplementation
*returnedbythe{@codeiterator}and{@codelistIterator}methods.
*Ifthevalueofthisfieldchangesunexpectedly,theiterator(orlist
*iterator)willthrowa{@codeConcurrentModificationException}in
*responsetothe{@codenext},{@coderemove},{@codeprevious},
*{@codeset}or{@codeadd}operations.Thisprovides
*fail-fastbehavior,ratherthannon-deterministicbehaviorin
*thefaceofconcurrentmodificationduringiteration.
*设计者认为,与其因为基本集合被并发修改从而使迭代产生不确定行为,不如尽早给出错误。
*
* Useofthisfieldbysubclassesisoptional.Ifasubclass
*wishestoprovidefail-fastiterators(andlistiterators),thenit
*merelyhastoincrementthisfieldinits{@codeadd(int,E)}and
*{@coderemove(int)}methods(andanyothermethodsthatitoverrides
*thatresultinstructuralmodificationstothelist).Asinglecallto
*{@codeadd(int,E)}or{@coderemove(int)}mustaddnomorethan
*onetothisfield,ortheiterators(andlistiterators)willthrow
*bogus{@codeConcurrentModificationExceptions}.Ifanimplementation
*doesnotwishtoprovidefail-fastiterators,thisfieldmaybe
*ignored.
*是否使用应需求决定。
*/
protectedtransientintmodCount=0;
} 看完上面的源码注解,已经大概能够知道modCount、expectedModCount以及checkForComodification()的作用了。 假如把基础集合当作一个银行账号,基础集合中的元素表示存款。那么modCount就相当于银行为每个账号做的消费记录,expectedModCount就相当于是账号持有人自己做的一份消费记录,一般银行和账号持有人自己做的消费记录都不会出错。 一旦银行那边的消费记录和自己手里的那份消费记录对不上,肯定是账号被盗用了。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。 声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。{@code
*while(hasNext())
*action.accept(next());
*}
*
*@paramactionTheactiontobeperformedforeachelement
*@throwsNullPointerExceptionifthespecifiedactionisnull
*@since1.8
*/
defaultvoidforEachRemaining(Consumeraction){
Objects.requireNonNull(action);
while(hasNext())
action.accept(next());
}
}
packagejava.util;
/**
*AnobjectthatimplementstheEnumerationinterfacegeneratesa
*seriesofelements,oneatatime.Successivecallstothe
*
nextElement
methodreturnsuccessiveelementsofthe
*series.
*
*for(Enumeration<E>e=v.elements();e.hasMoreElements();)
*System.out.println(e.nextElement());
*SequenceInputStream
.
*true
ifandonlyifthisenumerationobject
*containsatleastonemoreelementtoprovide;
*false
otherwise.
*/
booleanhasMoreElements();
/**
*Returnsthenextelementofthisenumerationifthisenumeration
*objecthasatleastonemoreelementtoprovide.
*
*@returnthenextelementofthisenumeration.
*@exceptionNoSuchElementExceptionifnomoreelementsexist.
*/
EnextElement();
}
/**
*Removefromtheunderlyingcollectionthelastelementreturnedbythisiterator
*(optionaloperation).
*移除当前迭代器上一次从基础集合中迭代的元素(可选操作)
*
*Thismethodcanbecalledonlyoncepercalltonext().
*调用remove()方法前必须先调用next()方法,调用完一次remove()方法后想要再次调用remove()方法,
*必须先调用next()方法。
*
*Thebehaviorofaniteratorisunspecifiediftheunderlyingcollectionismodifyedwhile
*theiterationisinprogressisanywayotherthanbycallthismethod.
*如果在迭代进行过程中修改了基础集合,则迭代器的行为是不确定的。
*/
publicstaticvoidmain(String[]args){
Collection
privateclassItrimplementsIterator
publicabstractclassAbstractList
finalvoidcheckForComodification(){
if(modCount!=expectedModCount)
thrownewConcurrentModificationException();
}