java Iterator接口和LIstIterator接口分析
java Iterator接口和LIstIterator接口分析
目录
1.Iterator接口
2.ListIterator
3.Iterator和ListIterator的区别 
正文
在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的。
我们知道,接口只是一种规范,当继承接口并实现其中的方法时,要遵循接口对方法的说明。
1.Iterator接口
Iterator接口取代了Java集合框架中的Enumeratrion。Iterators不同于enumerations的地方主要有两点:
Iterators允许调用者在迭代过程中从集合里移除元素;
方法名得到了改善。
Iterator源码如下:
/**
*Aniteratoroveracollection.{@codeIterator}takestheplaceof
*{@linkEnumeration}intheJavaCollectionsFramework.Iterators
*differfromenumerationsintwoways:
*Iteratorsallowthecallertoremoveelementsfromtheunderlyingcollectionduringtheiterationwithwell-definedsemantics.
*Methodnameshavebeenimproved.
*ThisinterfaceisamemberoftheJavaCollectionsFramework.
*@paramthetypeofelementsreturnedbythisiterator*/
publicinterfaceIterator{
/**
*Returns{@codetrue}iftheiterationhasmoreelements.
*(Inotherwords,returns{@codetrue}if{@link#next}would
*returnanelementratherthanthrowinganexception.)
*@return{@codetrue}iftheiterationhasmoreelements
*/
booleanhasNext();
/**
*Returnsthenextelementintheiteration.
*@returnthenextelementintheiteration
*@throwsNoSuchElementExceptioniftheiterationhasnomoreelements
*/
Enext();
/**
*Removesfromtheunderlyingcollectionthelastelementreturned
*bythisiterator(optionaloperation).Thismethodcanbecalled
*onlyoncepercallto{@link#next}.Thebehaviorofaniterator
*isunspecifiediftheunderlyingcollectionismodifiedwhilethe
*iterationisinprogressinanywayotherthanbycallingthis
*method.
*
*@implSpec
*Thedefaultimplementationthrowsaninstanceof
*{@linkUnsupportedOperationException}andperformsnootheraction.
*
*@throwsUnsupportedOperationExceptionifthe{@coderemove}
*operationisnotsupportedbythisiterator
*
*@throwsIllegalStateExceptionifthe{@codenext}methodhasnot
*yetbeencalled,orthe{@coderemove}methodhasalready
*beencalledafterthelastcalltothe{@codenext}
*method
*/
defaultvoidremove(){
thrownewUnsupportedOperationException("remove");
}
/**
*Performsthegivenactionforeachremainingelementuntilallelements
*havebeenprocessedortheactionthrowsanexception.Actionsare
*performedintheorderofiteration,ifthatorderisspecified.
*Exceptionsthrownbytheactionarerelayedtothecaller.
*
*@implSpec
*Thedefaultimplementationbehavesasif:
*
{@code
*while(hasNext())
*action.accept(next());
*}
*
*@paramactionTheactiontobeperformedforeachelement
*@throwsNullPointerExceptionifthespecifiedactionisnull
*@since1.8
*/
defaultvoidforEachRemaining(Consumeraction){
Objects.requireNonNull(action);
while(hasNext())
action.accept(next());
}
}  
Iterator接口定义了四个方法以及各个方法的功能,如果有类实现了这个接口,且实现了这些方法,这方法需要实现定义的功能,遵循这些规则:
1).hasNext()判断容器是否有下一个元素,有则返回true;
2).next()返回容器中的下一个元素;
3).remove()移除当前迭代器返回的最后一个元素。这个方法在每次调用next()方法之后只能调用一次;
4).Java8增加forEachRemaining方法,它可以实现对余下的所有元素执行指定的操作。
更详细的说明请阅读源码中的注释。
2.ListIterator
ListIterator在Iterator基础上提供了add、set、previous等对列表的操作。但是ListIterator跟Iterator一样,仍是在原列表上进行操作。
ListIterator源码如下:
/**
*Aniteratorforliststhatallowstheprogrammer
*totraversethelistineitherdirection,modify
*thelistduringiteration,andobtaintheiterator's
*currentpositioninthelist.A{@codeListIterator}
*hasnocurrentelement;itscursorpositionalways
*liesbetweentheelementthatwouldbereturnedbyacall
*to{@codeprevious()}andtheelementthatwouldbe
*returnedbyacallto{@codenext()}.
*Aniteratorforalistoflength{@coden}has{@coden+1}possible
*cursorpositions,asillustratedbythecarets({@code^})below:
*
*Element(0)Element(1)Element(2)...Element(n-1)
*cursorpositions:^^^^^
*
*Notethatthe{@link#remove}and{@link#set(Object)}methodsare
*notdefinedintermsofthecursorposition;theyaredefinedto
*operateonthelastelementreturnedbyacallto{@link#next}or
*{@link#previous()}.
*
*ThisinterfaceisamemberoftheJavaCollectionsFramework.*/
publicinterfaceListIteratorextendsIterator{
//QueryOperations
/**
*Returns{@codetrue}ifthislistiteratorhasmoreelementswhen
*traversingthelistintheforwarddirection.(Inotherwords,
*returns{@codetrue}if{@link#next}wouldreturnanelementrather
*thanthrowinganexception.)
*
*@return{@codetrue}ifthelistiteratorhasmoreelementswhen
*traversingthelistintheforwarddirection
*/
booleanhasNext();
/**
*Returnsthenextelementinthelistandadvancesthecursorposition.
*Thismethodmaybecalledrepeatedlytoiteratethroughthelist,
*orintermixedwithcallsto{@link#previous}togobackandforth.
*(Notethatalternatingcallsto{@codenext}and{@codeprevious}
*willreturnthesameelementrepeatedly.)
*
*@returnthenextelementinthelist
*@throwsNoSuchElementExceptioniftheiterationhasnonextelement
*/
Enext();
/**
*Returns{@codetrue}ifthislistiteratorhasmoreelementswhen
*traversingthelistinthereversedirection.(Inotherwords,
*returns{@codetrue}if{@link#previous}wouldreturnanelement
*ratherthanthrowinganexception.)
*
*@return{@codetrue}ifthelistiteratorhasmoreelementswhen
*traversingthelistinthereversedirection
*/
booleanhasPrevious();
/**
*Returnsthepreviouselementinthelistandmovesthecursor
*positionbackwards.Thismethodmaybecalledrepeatedlyto
*iteratethroughthelistbackwards,orintermixedwithcallsto
*{@link#next}togobackandforth.(Notethatalternatingcalls
*to{@codenext}and{@codeprevious}willreturnthesame
*elementrepeatedly.)
*
*@returnthepreviouselementinthelist
*@throwsNoSuchElementExceptioniftheiterationhasnoprevious
*element
*/
Eprevious();
/**
*Returnstheindexoftheelementthatwouldbereturnedbya
*subsequentcallto{@link#next}.(Returnslistsizeifthelist
*iteratorisattheendofthelist.)
*
*@returntheindexoftheelementthatwouldbereturnedbya
*subsequentcallto{@codenext},orlistsizeifthelist
*iteratorisattheendofthelist
*/
intnextIndex();
/**
*Returnstheindexoftheelementthatwouldbereturnedbya
*subsequentcallto{@link#previous}.(Returns-1ifthelist
*iteratorisatthebeginningofthelist.)
*
*@returntheindexoftheelementthatwouldbereturnedbya
*subsequentcallto{@codeprevious},or-1ifthelist
*iteratorisatthebeginningofthelist
*/
intpreviousIndex();
//ModificationOperations
/**
*Removesfromthelistthelastelementthatwasreturnedby{@link
*#next}or{@link#previous}(optionaloperation).Thiscallcan
*onlybemadeoncepercallto{@codenext}or{@codeprevious}.
*Itcanbemadeonlyif{@link#add}hasnotbeen
*calledafterthelastcallto{@codenext}or{@codeprevious}.
*
*@throwsUnsupportedOperationExceptionifthe{@coderemove}
*operationisnotsupportedbythislistiterator
*@throwsIllegalStateExceptionifneither{@codenext}nor
*{@codeprevious}havebeencalled,or{@coderemove}or
*{@codeadd}havebeencalledafterthelastcallto
*{@codenext}or{@codeprevious}
*/
voidremove();
/**
*Replacesthelastelementreturnedby{@link#next}or
*{@link#previous}withthespecifiedelement(optionaloperation).
*Thiscallcanbemadeonlyifneither{@link#remove}nor{@link
*#add}havebeencalledafterthelastcallto{@codenext}or
*{@codeprevious}.
*
*@parametheelementwithwhichtoreplacethelastelementreturnedby
*{@codenext}or{@codeprevious}
*@throwsUnsupportedOperationExceptionifthe{@codeset}operation
*isnotsupportedbythislistiterator
*@throwsClassCastExceptioniftheclassofthespecifiedelement
*preventsitfrombeingaddedtothislist
*@throwsIllegalArgumentExceptionifsomeaspectofthespecified
*elementpreventsitfrombeingaddedtothislist
*@throwsIllegalStateExceptionifneither{@codenext}nor
*{@codeprevious}havebeencalled,or{@coderemove}or
*{@codeadd}havebeencalledafterthelastcallto
*{@codenext}or{@codeprevious}
*/
voidset(Ee);
/**
*Insertsthespecifiedelementintothelist(optionaloperation).
*Theelementisinsertedimmediatelybeforetheelementthat
*wouldbereturnedby{@link#next},ifany,andaftertheelement
*thatwouldbereturnedby{@link#previous},ifany.(Ifthe
*listcontainsnoelements,thenewelementbecomesthesoleelement
*onthelist.)Thenewelementisinsertedbeforetheimplicit
*cursor:asubsequentcallto{@codenext}wouldbeunaffected,anda
*subsequentcallto{@codeprevious}wouldreturnthenewelement.
*(Thiscallincreasesbyonethevaluethatwouldbereturnedbya
*callto{@codenextIndex}or{@codepreviousIndex}.)
*
*@parametheelementtoinsert
*@throwsUnsupportedOperationExceptionifthe{@codeadd}methodis
*notsupportedbythislistiterator
*@throwsClassCastExceptioniftheclassofthespecifiedelement
*preventsitfrombeingaddedtothislist
*@throwsIllegalArgumentExceptionifsomeaspectofthiselement
*preventsitfrombeingaddedtothislist
*/
voidadd(Ee);
}
  
ListIterator的功能更加强大,定义的方法有:
1).hasNext()向前遍历时,如果有下一个元素返回真;
2).next()返回下一个元素的值,并将指针加1;
3).hasPrevious()向相反方向遍历时,如果还有元素返回真;
4).previous()返回上一个元素的值,并将指针前移1;
5).nextIndex()返回此时调用next()方法时返回的元素的索引;
6).previousIndex()返回此时调用previous()方法时返回的元素的索引;
7).remove()移除最近一次调用next()或previous()方法返回的元素(可选);
8).set(Ee)用元素e将如果此时调用next()或previous()方法返回的元素替换掉;
9).add(Ee)添加元素到此时调用next()返回的元素之前,或此时调用previous()返回的元素之后。
更详细的说明请阅读源码中的注释。
3.Iterator和ListIterator的区别
Iterator和ListIterator的方法对比如下表:
 Iterator ListIterator hasNext() next() remove() forEachRemaining(Consumer action)
 
 
 
  
 
 
hasNext() 
覆盖 
 
 
next() 
覆盖 
 
 
remove() 
覆盖 
 
 
forEachRemaining(Consumer action) 
继承 
 
  
hasPrevious() 
  
 
  
previous() 
  
 
  
nextIndex() 
  
 
  
previousIndex() 
  
 
  
set(Ee) 
  
 
  
add(Ee) 
  
二者的不同之处主要有:
1).Iterator只能单向移动,ListIterator可以双向移动;
2).ListIterator可以删除、替换或添加元素,而Iterator只能删除元素;
3).ListIterator可以返回当前(调用next()或previous()返回的)元素的索引,而Iterator不能。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!