Collections.java 239 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628
  1. /* Collections.java -- Utility class with methods to operate on collections
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.io.Serializable;
  35. /**
  36. * Utility class consisting of static methods that operate on, or return
  37. * Collections. Contains methods to sort, search, reverse, fill and shuffle
  38. * Collections, methods to facilitate interoperability with legacy APIs that
  39. * are unaware of collections, a method to return a list which consists of
  40. * multiple copies of one element, and methods which "wrap" collections to give
  41. * them extra properties, such as thread-safety and unmodifiability.
  42. * <p>
  43. *
  44. * All methods which take a collection throw a {@link NullPointerException} if
  45. * that collection is null. Algorithms which can change a collection may, but
  46. * are not required, to throw the {@link UnsupportedOperationException} that
  47. * the underlying collection would throw during an attempt at modification.
  48. * For example,
  49. * <code>Collections.singleton("").addAll(Collections.EMPTY_SET)</code>
  50. * does not throw a exception, even though addAll is an unsupported operation
  51. * on a singleton; the reason for this is that addAll did not attempt to
  52. * modify the set.
  53. *
  54. * @author Original author unknown
  55. * @author Eric Blake (ebb9@email.byu.edu)
  56. * @author Tom Tromey (tromey@redhat.com)
  57. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  58. * @see Collection
  59. * @see Set
  60. * @see List
  61. * @see Map
  62. * @see Arrays
  63. * @since 1.2
  64. * @status updated to 1.5
  65. */
  66. public class Collections
  67. {
  68. /**
  69. * Constant used to decide cutoff for when a non-RandomAccess list should
  70. * be treated as sequential-access. Basically, quadratic behavior is
  71. * acceptable for small lists when the overhead is so small in the first
  72. * place. I arbitrarily set it to 16, so it may need some tuning.
  73. */
  74. private static final int LARGE_LIST_SIZE = 16;
  75. /**
  76. * Determines if a list should be treated as a sequential-access one.
  77. * Rather than the old method of JDK 1.3 of assuming only instanceof
  78. * AbstractSequentialList should be sequential, this uses the new method
  79. * of JDK 1.4 of assuming anything that does NOT implement RandomAccess
  80. * and exceeds a large (unspecified) size should be sequential.
  81. *
  82. * @param l the list to check
  83. * @return <code>true</code> if it should be treated as sequential-access
  84. */
  85. private static boolean isSequential(List<?> l)
  86. {
  87. return ! (l instanceof RandomAccess) && l.size() > LARGE_LIST_SIZE;
  88. }
  89. /**
  90. * This class is non-instantiable.
  91. */
  92. private Collections()
  93. {
  94. }
  95. /**
  96. * An immutable, serializable, empty Set.
  97. * @see Serializable
  98. */
  99. public static final Set EMPTY_SET = new EmptySet();
  100. /**
  101. * Returns an immutable, serializable parameterized empty set.
  102. * Unlike the constant <code>EMPTY_SET</code>, the set returned by
  103. * this method is type-safe.
  104. *
  105. * @return an empty parameterized set.
  106. * @since 1.5
  107. */
  108. @SuppressWarnings("unchecked")
  109. public static final <T> Set<T> emptySet()
  110. {
  111. return (Set<T>) EMPTY_SET;
  112. }
  113. /**
  114. * The implementation of {@link #EMPTY_SET}. This class name is required
  115. * for compatibility with Sun's JDK serializability.
  116. *
  117. * @author Eric Blake (ebb9@email.byu.edu)
  118. */
  119. private static final class EmptySet<T> extends AbstractSet<T>
  120. implements Serializable
  121. {
  122. /**
  123. * Compatible with JDK 1.4.
  124. */
  125. private static final long serialVersionUID = 1582296315990362920L;
  126. /**
  127. * A private constructor adds overhead.
  128. */
  129. EmptySet()
  130. {
  131. }
  132. /**
  133. * The size: always 0!
  134. * @return 0.
  135. */
  136. public int size()
  137. {
  138. return 0;
  139. }
  140. /**
  141. * Returns an iterator that does not iterate.
  142. * @return A non-iterating iterator.
  143. */
  144. // This is really cheating! I think it's perfectly valid, though.
  145. @SuppressWarnings("unchecked")
  146. public Iterator<T> iterator()
  147. {
  148. return (Iterator<T>) EMPTY_LIST.iterator();
  149. }
  150. // The remaining methods are optional, but provide a performance
  151. // advantage by not allocating unnecessary iterators in AbstractSet.
  152. /**
  153. * The empty set never contains anything.
  154. * @param o The object to search for.
  155. * @return <code>false</code>.
  156. */
  157. public boolean contains(Object o)
  158. {
  159. return false;
  160. }
  161. /**
  162. * This is true only if the given collection is also empty.
  163. * @param c The collection of objects which are to be compared
  164. * against the members of this set.
  165. * @return <code>true</code> if c is empty.
  166. */
  167. public boolean containsAll(Collection<?> c)
  168. {
  169. return c.isEmpty();
  170. }
  171. /**
  172. * Equal only if the other set is empty.
  173. * @param o The object to compare with this set.
  174. * @return <code>true</code> if o is an empty instance of <code>Set</code>.
  175. */
  176. public boolean equals(Object o)
  177. {
  178. return o instanceof Set<?> && ((Set<?>) o).isEmpty();
  179. }
  180. /**
  181. * The hashcode is always 0.
  182. * @return 0.
  183. */
  184. public int hashCode()
  185. {
  186. return 0;
  187. }
  188. /**
  189. * Always succeeds with a <code>false</code> result.
  190. * @param o The object to remove.
  191. * @return <code>false</code>.
  192. */
  193. public boolean remove(Object o)
  194. {
  195. return false;
  196. }
  197. /**
  198. * Always succeeds with a <code>false</code> result.
  199. * @param c The collection of objects which should
  200. * all be removed from this set.
  201. * @return <code>false</code>.
  202. */
  203. public boolean removeAll(Collection<?> c)
  204. {
  205. return false;
  206. }
  207. /**
  208. * Always succeeds with a <code>false</code> result.
  209. * @param c The collection of objects which should
  210. * all be retained within this set.
  211. * @return <code>false</code>.
  212. */
  213. public boolean retainAll(Collection<?> c)
  214. {
  215. return false;
  216. }
  217. /**
  218. * The array is always empty.
  219. * @return A new array with a size of 0.
  220. */
  221. public Object[] toArray()
  222. {
  223. return new Object[0];
  224. }
  225. /**
  226. * We don't even need to use reflection!
  227. * @param a An existing array, which can be empty.
  228. * @return The original array with any existing
  229. * initial element set to null.
  230. */
  231. public <E> E[] toArray(E[] a)
  232. {
  233. if (a.length > 0)
  234. a[0] = null;
  235. return a;
  236. }
  237. /**
  238. * The string never changes.
  239. *
  240. * @return the string "[]".
  241. */
  242. public String toString()
  243. {
  244. return "[]";
  245. }
  246. } // class EmptySet
  247. /**
  248. * An immutable, serializable, empty List, which implements RandomAccess.
  249. * @see Serializable
  250. * @see RandomAccess
  251. */
  252. public static final List EMPTY_LIST = new EmptyList();
  253. /**
  254. * Returns an immutable, serializable parameterized empty list.
  255. * Unlike the constant <code>EMPTY_LIST</code>, the list returned by
  256. * this method is type-safe.
  257. *
  258. * @return an empty parameterized list.
  259. * @since 1.5
  260. */
  261. @SuppressWarnings("unchecked")
  262. public static final <T> List<T> emptyList()
  263. {
  264. return (List<T>) EMPTY_LIST;
  265. }
  266. /**
  267. * The implementation of {@link #EMPTY_LIST}. This class name is required
  268. * for compatibility with Sun's JDK serializability.
  269. *
  270. * @author Eric Blake (ebb9@email.byu.edu)
  271. */
  272. private static final class EmptyList<T> extends AbstractList<T>
  273. implements Serializable, RandomAccess
  274. {
  275. /**
  276. * Compatible with JDK 1.4.
  277. */
  278. private static final long serialVersionUID = 8842843931221139166L;
  279. /**
  280. * A private constructor adds overhead.
  281. */
  282. EmptyList()
  283. {
  284. }
  285. /**
  286. * The size is always 0.
  287. * @return 0.
  288. */
  289. public int size()
  290. {
  291. return 0;
  292. }
  293. /**
  294. * No matter the index, it is out of bounds. This
  295. * method never returns, throwing an exception instead.
  296. *
  297. * @param index The index of the element to retrieve.
  298. * @return the object at the specified index.
  299. * @throws IndexOutOfBoundsException as any given index
  300. * is outside the bounds of an empty array.
  301. */
  302. public T get(int index)
  303. {
  304. throw new IndexOutOfBoundsException();
  305. }
  306. // The remaining methods are optional, but provide a performance
  307. // advantage by not allocating unnecessary iterators in AbstractList.
  308. /**
  309. * Never contains anything.
  310. * @param o The object to search for.
  311. * @return <code>false</code>.
  312. */
  313. public boolean contains(Object o)
  314. {
  315. return false;
  316. }
  317. /**
  318. * This is true only if the given collection is also empty.
  319. * @param c The collection of objects, which should be compared
  320. * against the members of this list.
  321. * @return <code>true</code> if c is also empty.
  322. */
  323. public boolean containsAll(Collection<?> c)
  324. {
  325. return c.isEmpty();
  326. }
  327. /**
  328. * Equal only if the other list is empty.
  329. * @param o The object to compare against this list.
  330. * @return <code>true</code> if o is also an empty instance of
  331. * <code>List</code>.
  332. */
  333. public boolean equals(Object o)
  334. {
  335. return o instanceof List<?> && ((List<?>) o).isEmpty();
  336. }
  337. /**
  338. * The hashcode is always 1.
  339. * @return 1.
  340. */
  341. public int hashCode()
  342. {
  343. return 1;
  344. }
  345. /**
  346. * Returns -1.
  347. * @param o The object to search for.
  348. * @return -1.
  349. */
  350. public int indexOf(Object o)
  351. {
  352. return -1;
  353. }
  354. /**
  355. * Returns -1.
  356. * @param o The object to search for.
  357. * @return -1.
  358. */
  359. public int lastIndexOf(Object o)
  360. {
  361. return -1;
  362. }
  363. /**
  364. * Always succeeds with <code>false</code> result.
  365. * @param o The object to remove.
  366. * @return -1.
  367. */
  368. public boolean remove(Object o)
  369. {
  370. return false;
  371. }
  372. /**
  373. * Always succeeds with <code>false</code> result.
  374. * @param c The collection of objects which should
  375. * all be removed from this list.
  376. * @return <code>false</code>.
  377. */
  378. public boolean removeAll(Collection<?> c)
  379. {
  380. return false;
  381. }
  382. /**
  383. * Always succeeds with <code>false</code> result.
  384. * @param c The collection of objects which should
  385. * all be retained within this list.
  386. * @return <code>false</code>.
  387. */
  388. public boolean retainAll(Collection<?> c)
  389. {
  390. return false;
  391. }
  392. /**
  393. * The array is always empty.
  394. * @return A new array with a size of 0.
  395. */
  396. public Object[] toArray()
  397. {
  398. return new Object[0];
  399. }
  400. /**
  401. * We don't even need to use reflection!
  402. * @param a An existing array, which can be empty.
  403. * @return The original array with any existing
  404. * initial element set to null.
  405. */
  406. public <E> E[] toArray(E[] a)
  407. {
  408. if (a.length > 0)
  409. a[0] = null;
  410. return a;
  411. }
  412. /**
  413. * The string never changes.
  414. *
  415. * @return the string "[]".
  416. */
  417. public String toString()
  418. {
  419. return "[]";
  420. }
  421. } // class EmptyList
  422. /**
  423. * An immutable, serializable, empty Map.
  424. * @see Serializable
  425. */
  426. public static final Map EMPTY_MAP = new EmptyMap();
  427. /**
  428. * Returns an immutable, serializable parameterized empty map.
  429. * Unlike the constant <code>EMPTY_MAP</code>, the map returned by
  430. * this method is type-safe.
  431. *
  432. * @return an empty parameterized map.
  433. * @since 1.5
  434. */
  435. @SuppressWarnings("unchecked")
  436. public static final <K,V> Map<K,V> emptyMap()
  437. {
  438. return (Map<K,V>) EMPTY_MAP;
  439. }
  440. /**
  441. * The implementation of {@link #EMPTY_MAP}. This class name is required
  442. * for compatibility with Sun's JDK serializability.
  443. *
  444. * @author Eric Blake (ebb9@email.byu.edu)
  445. */
  446. private static final class EmptyMap<K, V> extends AbstractMap<K, V>
  447. implements Serializable
  448. {
  449. /**
  450. * Compatible with JDK 1.4.
  451. */
  452. private static final long serialVersionUID = 6428348081105594320L;
  453. /**
  454. * A private constructor adds overhead.
  455. */
  456. EmptyMap()
  457. {
  458. }
  459. /**
  460. * There are no entries.
  461. * @return The empty set.
  462. */
  463. @SuppressWarnings("unchecked")
  464. public Set<Map.Entry<K, V>> entrySet()
  465. {
  466. return (Set<Map.Entry<K, V>>) EMPTY_SET;
  467. }
  468. // The remaining methods are optional, but provide a performance
  469. // advantage by not allocating unnecessary iterators in AbstractMap.
  470. /**
  471. * No entries!
  472. * @param key The key to search for.
  473. * @return <code>false</code>.
  474. */
  475. public boolean containsKey(Object key)
  476. {
  477. return false;
  478. }
  479. /**
  480. * No entries!
  481. * @param value The value to search for.
  482. * @return <code>false</code>.
  483. */
  484. public boolean containsValue(Object value)
  485. {
  486. return false;
  487. }
  488. /**
  489. * Equal to all empty maps.
  490. * @param o The object o to compare against this map.
  491. * @return <code>true</code> if o is also an empty instance of
  492. * <code>Map</code>.
  493. */
  494. public boolean equals(Object o)
  495. {
  496. return o instanceof Map<?,?> && ((Map<?,?>) o).isEmpty();
  497. }
  498. /**
  499. * No mappings, so this returns null.
  500. * @param o The key of the object to retrieve.
  501. * @return null.
  502. */
  503. public V get(Object o)
  504. {
  505. return null;
  506. }
  507. /**
  508. * The hashcode is always 0.
  509. * @return 0.
  510. */
  511. public int hashCode()
  512. {
  513. return 0;
  514. }
  515. /**
  516. * No entries.
  517. * @return The empty set.
  518. */
  519. @SuppressWarnings("unchecked")
  520. public Set<K> keySet()
  521. {
  522. return (Set<K>) EMPTY_SET;
  523. }
  524. /**
  525. * Remove always succeeds, with null result.
  526. * @param o The key of the mapping to remove.
  527. * @return null, as there is never a mapping for o.
  528. */
  529. public V remove(Object o)
  530. {
  531. return null;
  532. }
  533. /**
  534. * Size is always 0.
  535. * @return 0.
  536. */
  537. public int size()
  538. {
  539. return 0;
  540. }
  541. /**
  542. * No entries. Technically, EMPTY_SET, while more specific than a general
  543. * Collection, will work. Besides, that's what the JDK uses!
  544. * @return The empty set.
  545. */
  546. @SuppressWarnings("unchecked")
  547. public Collection<V> values()
  548. {
  549. return (Collection<V>) EMPTY_SET;
  550. }
  551. /**
  552. * The string never changes.
  553. *
  554. * @return the string "[]".
  555. */
  556. public String toString()
  557. {
  558. return "[]";
  559. }
  560. } // class EmptyMap
  561. /**
  562. * Compare two objects with or without a Comparator. If c is null, uses the
  563. * natural ordering. Slightly slower than doing it inline if the JVM isn't
  564. * clever, but worth it for removing a duplicate of the search code.
  565. * Note: This code is also used in Arrays (for sort as well as search).
  566. */
  567. static final <T> int compare(T o1, T o2, Comparator<? super T> c)
  568. {
  569. return c == null ? ((Comparable) o1).compareTo(o2) : c.compare(o1, o2);
  570. }
  571. /**
  572. * Perform a binary search of a List for a key, using the natural ordering of
  573. * the elements. The list must be sorted (as by the sort() method) - if it is
  574. * not, the behavior of this method is undefined, and may be an infinite
  575. * loop. Further, the key must be comparable with every item in the list. If
  576. * the list contains the key more than once, any one of them may be found.
  577. * <p>
  578. *
  579. * This algorithm behaves in log(n) time for {@link RandomAccess} lists,
  580. * and uses a linear search with O(n) link traversals and log(n) comparisons
  581. * with {@link AbstractSequentialList} lists. Note: although the
  582. * specification allows for an infinite loop if the list is unsorted, it will
  583. * not happen in this (Classpath) implementation.
  584. *
  585. * @param l the list to search (must be sorted)
  586. * @param key the value to search for
  587. * @return the index at which the key was found, or -n-1 if it was not
  588. * found, where n is the index of the first value higher than key or
  589. * a.length if there is no such value
  590. * @throws ClassCastException if key could not be compared with one of the
  591. * elements of l
  592. * @throws NullPointerException if a null element has compareTo called
  593. * @see #sort(List)
  594. */
  595. public static <T> int binarySearch(List<? extends Comparable<? super T>> l,
  596. T key)
  597. {
  598. return binarySearch(l, key, null);
  599. }
  600. /**
  601. * Perform a binary search of a List for a key, using a supplied Comparator.
  602. * The list must be sorted (as by the sort() method with the same Comparator)
  603. * - if it is not, the behavior of this method is undefined, and may be an
  604. * infinite loop. Further, the key must be comparable with every item in the
  605. * list. If the list contains the key more than once, any one of them may be
  606. * found. If the comparator is null, the elements' natural ordering is used.
  607. * <p>
  608. *
  609. * This algorithm behaves in log(n) time for {@link RandomAccess} lists,
  610. * and uses a linear search with O(n) link traversals and log(n) comparisons
  611. * with {@link AbstractSequentialList} lists. Note: although the
  612. * specification allows for an infinite loop if the list is unsorted, it will
  613. * not happen in this (Classpath) implementation.
  614. *
  615. * @param l the list to search (must be sorted)
  616. * @param key the value to search for
  617. * @param c the comparator by which the list is sorted
  618. * @return the index at which the key was found, or -n-1 if it was not
  619. * found, where n is the index of the first value higher than key or
  620. * a.length if there is no such value
  621. * @throws ClassCastException if key could not be compared with one of the
  622. * elements of l
  623. * @throws NullPointerException if a null element is compared with natural
  624. * ordering (only possible when c is null)
  625. * @see #sort(List, Comparator)
  626. */
  627. public static <T> int binarySearch(List<? extends T> l, T key,
  628. Comparator<? super T> c)
  629. {
  630. int pos = 0;
  631. int low = 0;
  632. int hi = l.size() - 1;
  633. // We use a linear search with log(n) comparisons using an iterator
  634. // if the list is sequential-access.
  635. if (isSequential(l))
  636. {
  637. ListIterator<T> itr = ((List<T>) l).listIterator();
  638. int i = 0;
  639. T o = itr.next(); // Assumes list is not empty (see isSequential)
  640. boolean forward = true;
  641. while (low <= hi)
  642. {
  643. pos = (low + hi) >>> 1;
  644. if (i < pos)
  645. {
  646. if (!forward)
  647. itr.next(); // Changing direction first.
  648. for ( ; i != pos; i++, o = itr.next())
  649. ;
  650. forward = true;
  651. }
  652. else
  653. {
  654. if (forward)
  655. itr.previous(); // Changing direction first.
  656. for ( ; i != pos; i--, o = itr.previous())
  657. ;
  658. forward = false;
  659. }
  660. final int d = compare(o, key, c);
  661. if (d == 0)
  662. return pos;
  663. else if (d > 0)
  664. hi = pos - 1;
  665. else
  666. // This gets the insertion point right on the last loop
  667. low = ++pos;
  668. }
  669. }
  670. else
  671. {
  672. while (low <= hi)
  673. {
  674. pos = (low + hi) >>> 1;
  675. final int d = compare(((List<T>) l).get(pos), key, c);
  676. if (d == 0)
  677. return pos;
  678. else if (d > 0)
  679. hi = pos - 1;
  680. else
  681. // This gets the insertion point right on the last loop
  682. low = ++pos;
  683. }
  684. }
  685. // If we failed to find it, we do the same whichever search we did.
  686. return -pos - 1;
  687. }
  688. /**
  689. * Copy one list to another. If the destination list is longer than the
  690. * source list, the remaining elements are unaffected. This method runs in
  691. * linear time.
  692. *
  693. * @param dest the destination list
  694. * @param source the source list
  695. * @throws IndexOutOfBoundsException if the destination list is shorter
  696. * than the source list (the destination will be unmodified)
  697. * @throws UnsupportedOperationException if dest.listIterator() does not
  698. * support the set operation
  699. */
  700. public static <T> void copy(List<? super T> dest, List<? extends T> source)
  701. {
  702. int pos = source.size();
  703. if (dest.size() < pos)
  704. throw new IndexOutOfBoundsException("Source does not fit in dest");
  705. Iterator<? extends T> i1 = source.iterator();
  706. ListIterator<? super T> i2 = dest.listIterator();
  707. while (--pos >= 0)
  708. {
  709. i2.next();
  710. i2.set(i1.next());
  711. }
  712. }
  713. /**
  714. * Returns an Enumeration over a collection. This allows interoperability
  715. * with legacy APIs that require an Enumeration as input.
  716. *
  717. * @param c the Collection to iterate over
  718. * @return an Enumeration backed by an Iterator over c
  719. */
  720. public static <T> Enumeration<T> enumeration(Collection<T> c)
  721. {
  722. final Iterator<T> i = c.iterator();
  723. return new Enumeration<T>()
  724. {
  725. /**
  726. * Returns <code>true</code> if there are more elements to
  727. * be enumerated.
  728. *
  729. * @return The result of <code>hasNext()</code>
  730. * called on the underlying iterator.
  731. */
  732. public final boolean hasMoreElements()
  733. {
  734. return i.hasNext();
  735. }
  736. /**
  737. * Returns the next element to be enumerated.
  738. *
  739. * @return The result of <code>next()</code>
  740. * called on the underlying iterator.
  741. */
  742. public final T nextElement()
  743. {
  744. return i.next();
  745. }
  746. };
  747. }
  748. /**
  749. * Replace every element of a list with a given value. This method runs in
  750. * linear time.
  751. *
  752. * @param l the list to fill.
  753. * @param val the object to vill the list with.
  754. * @throws UnsupportedOperationException if l.listIterator() does not
  755. * support the set operation.
  756. */
  757. public static <T> void fill(List<? super T> l, T val)
  758. {
  759. ListIterator<? super T> itr = l.listIterator();
  760. for (int i = l.size() - 1; i >= 0; --i)
  761. {
  762. itr.next();
  763. itr.set(val);
  764. }
  765. }
  766. /**
  767. * Returns the starting index where the specified sublist first occurs
  768. * in a larger list, or -1 if there is no matching position. If
  769. * <code>target.size() &gt; source.size()</code>, this returns -1,
  770. * otherwise this implementation uses brute force, checking for
  771. * <code>source.sublist(i, i + target.size()).equals(target)</code>
  772. * for all possible i.
  773. *
  774. * @param source the list to search
  775. * @param target the sublist to search for
  776. * @return the index where found, or -1
  777. * @since 1.4
  778. */
  779. public static int indexOfSubList(List<?> source, List<?> target)
  780. {
  781. int ssize = source.size();
  782. for (int i = 0, j = target.size(); j <= ssize; i++, j++)
  783. if (source.subList(i, j).equals(target))
  784. return i;
  785. return -1;
  786. }
  787. /**
  788. * Returns the starting index where the specified sublist last occurs
  789. * in a larger list, or -1 if there is no matching position. If
  790. * <code>target.size() &gt; source.size()</code>, this returns -1,
  791. * otherwise this implementation uses brute force, checking for
  792. * <code>source.sublist(i, i + target.size()).equals(target)</code>
  793. * for all possible i.
  794. *
  795. * @param source the list to search
  796. * @param target the sublist to search for
  797. * @return the index where found, or -1
  798. * @since 1.4
  799. */
  800. public static int lastIndexOfSubList(List<?> source, List<?> target)
  801. {
  802. int ssize = source.size();
  803. for (int i = ssize - target.size(), j = ssize; i >= 0; i--, j--)
  804. if (source.subList(i, j).equals(target))
  805. return i;
  806. return -1;
  807. }
  808. /**
  809. * Returns an ArrayList holding the elements visited by a given
  810. * Enumeration. This method exists for interoperability between legacy
  811. * APIs and the new Collection API.
  812. *
  813. * @param e the enumeration to put in a list
  814. * @return a list containing the enumeration elements
  815. * @see ArrayList
  816. * @since 1.4
  817. */
  818. public static <T> ArrayList<T> list(Enumeration<T> e)
  819. {
  820. ArrayList<T> l = new ArrayList<T>();
  821. while (e.hasMoreElements())
  822. l.add(e.nextElement());
  823. return l;
  824. }
  825. /**
  826. * Find the maximum element in a Collection, according to the natural
  827. * ordering of the elements. This implementation iterates over the
  828. * Collection, so it works in linear time.
  829. *
  830. * @param c the Collection to find the maximum element of
  831. * @return the maximum element of c
  832. * @exception NoSuchElementException if c is empty
  833. * @exception ClassCastException if elements in c are not mutually comparable
  834. * @exception NullPointerException if null.compareTo is called
  835. */
  836. public static <T extends Object & Comparable<? super T>>
  837. T max(Collection<? extends T> c)
  838. {
  839. return max(c, null);
  840. }
  841. /**
  842. * Find the maximum element in a Collection, according to a specified
  843. * Comparator. This implementation iterates over the Collection, so it
  844. * works in linear time.
  845. *
  846. * @param c the Collection to find the maximum element of
  847. * @param order the Comparator to order the elements by, or null for natural
  848. * ordering
  849. * @return the maximum element of c
  850. * @throws NoSuchElementException if c is empty
  851. * @throws ClassCastException if elements in c are not mutually comparable
  852. * @throws NullPointerException if null is compared by natural ordering
  853. * (only possible when order is null)
  854. */
  855. public static <T> T max(Collection<? extends T> c,
  856. Comparator<? super T> order)
  857. {
  858. Iterator<? extends T> itr = c.iterator();
  859. T max = itr.next(); // throws NoSuchElementException
  860. int csize = c.size();
  861. for (int i = 1; i < csize; i++)
  862. {
  863. T o = itr.next();
  864. if (compare(max, o, order) < 0)
  865. max = o;
  866. }
  867. return max;
  868. }
  869. /**
  870. * Find the minimum element in a Collection, according to the natural
  871. * ordering of the elements. This implementation iterates over the
  872. * Collection, so it works in linear time.
  873. *
  874. * @param c the Collection to find the minimum element of
  875. * @return the minimum element of c
  876. * @throws NoSuchElementException if c is empty
  877. * @throws ClassCastException if elements in c are not mutually comparable
  878. * @throws NullPointerException if null.compareTo is called
  879. */
  880. public static <T extends Object & Comparable<? super T>>
  881. T min(Collection<? extends T> c)
  882. {
  883. return min(c, null);
  884. }
  885. /**
  886. * Find the minimum element in a Collection, according to a specified
  887. * Comparator. This implementation iterates over the Collection, so it
  888. * works in linear time.
  889. *
  890. * @param c the Collection to find the minimum element of
  891. * @param order the Comparator to order the elements by, or null for natural
  892. * ordering
  893. * @return the minimum element of c
  894. * @throws NoSuchElementException if c is empty
  895. * @throws ClassCastException if elements in c are not mutually comparable
  896. * @throws NullPointerException if null is compared by natural ordering
  897. * (only possible when order is null)
  898. */
  899. public static <T> T min(Collection<? extends T> c,
  900. Comparator<? super T> order)
  901. {
  902. Iterator<? extends T> itr = c.iterator();
  903. T min = itr.next(); // throws NoSuchElementExcception
  904. int csize = c.size();
  905. for (int i = 1; i < csize; i++)
  906. {
  907. T o = itr.next();
  908. if (compare(min, o, order) > 0)
  909. min = o;
  910. }
  911. return min;
  912. }
  913. /**
  914. * Creates an immutable list consisting of the same object repeated n times.
  915. * The returned object is tiny, consisting of only a single reference to the
  916. * object and a count of the number of elements. It is Serializable, and
  917. * implements RandomAccess. You can use it in tandem with List.addAll for
  918. * fast list construction.
  919. *
  920. * @param n the number of times to repeat the object
  921. * @param o the object to repeat
  922. * @return a List consisting of n copies of o
  923. * @throws IllegalArgumentException if n &lt; 0
  924. * @see List#addAll(Collection)
  925. * @see Serializable
  926. * @see RandomAccess
  927. */
  928. public static <T> List<T> nCopies(final int n, final T o)
  929. {
  930. return new CopiesList<T>(n, o);
  931. }
  932. /**
  933. * The implementation of {@link #nCopies(int, Object)}. This class name
  934. * is required for compatibility with Sun's JDK serializability.
  935. *
  936. * @author Eric Blake (ebb9@email.byu.edu)
  937. */
  938. private static final class CopiesList<T> extends AbstractList<T>
  939. implements Serializable, RandomAccess
  940. {
  941. /**
  942. * Compatible with JDK 1.4.
  943. */
  944. private static final long serialVersionUID = 2739099268398711800L;
  945. /**
  946. * The count of elements in this list.
  947. * @serial the list size
  948. */
  949. private final int n;
  950. /**
  951. * The repeated list element.
  952. * @serial the list contents
  953. */
  954. private final T element;
  955. /**
  956. * Constructs the list.
  957. *
  958. * @param n the count
  959. * @param o the object
  960. * @throws IllegalArgumentException if n &lt; 0
  961. */
  962. CopiesList(int n, T o)
  963. {
  964. if (n < 0)
  965. throw new IllegalArgumentException();
  966. this.n = n;
  967. element = o;
  968. }
  969. /**
  970. * The size is fixed.
  971. * @return The size of the list.
  972. */
  973. public int size()
  974. {
  975. return n;
  976. }
  977. /**
  978. * The same element is returned.
  979. * @param index The index of the element to be returned (irrelevant
  980. * as the list contains only copies of <code>element</code>).
  981. * @return The element used by this list.
  982. */
  983. public T get(int index)
  984. {
  985. if (index < 0 || index >= n)
  986. throw new IndexOutOfBoundsException();
  987. return element;
  988. }
  989. // The remaining methods are optional, but provide a performance
  990. // advantage by not allocating unnecessary iterators in AbstractList.
  991. /**
  992. * This list only contains one element.
  993. * @param o The object to search for.
  994. * @return <code>true</code> if o is the element used by this list.
  995. */
  996. public boolean contains(Object o)
  997. {
  998. return n > 0 && equals(o, element);
  999. }
  1000. /**
  1001. * The index is either 0 or -1.
  1002. * @param o The object to find the index of.
  1003. * @return 0 if <code>o == element</code>, -1 if not.
  1004. */
  1005. public int indexOf(Object o)
  1006. {
  1007. return (n > 0 && equals(o, element)) ? 0 : -1;
  1008. }
  1009. /**
  1010. * The index is either n-1 or -1.
  1011. * @param o The object to find the last index of.
  1012. * @return The last index in the list if <code>o == element</code>,
  1013. * -1 if not.
  1014. */
  1015. public int lastIndexOf(Object o)
  1016. {
  1017. return equals(o, element) ? n - 1 : -1;
  1018. }
  1019. /**
  1020. * A subList is just another CopiesList.
  1021. * @param from The starting bound of the sublist.
  1022. * @param to The ending bound of the sublist.
  1023. * @return A list of copies containing <code>from - to</code>
  1024. * elements, all of which are equal to the element
  1025. * used by this list.
  1026. */
  1027. public List<T> subList(int from, int to)
  1028. {
  1029. if (from < 0 || to > n)
  1030. throw new IndexOutOfBoundsException();
  1031. return new CopiesList<T>(to - from, element);
  1032. }
  1033. /**
  1034. * The array is easy.
  1035. * @return An array of size n filled with copies of
  1036. * the element used by this list.
  1037. */
  1038. public Object[] toArray()
  1039. {
  1040. Object[] a = new Object[n];
  1041. Arrays.fill(a, element);
  1042. return a;
  1043. }
  1044. /**
  1045. * The string is easy to generate.
  1046. * @return A string representation of the list.
  1047. */
  1048. public String toString()
  1049. {
  1050. CPStringBuilder r = new CPStringBuilder("{");
  1051. for (int i = n - 1; --i > 0; )
  1052. r.append(element).append(", ");
  1053. r.append(element).append("}");
  1054. return r.toString();
  1055. }
  1056. } // class CopiesList
  1057. /**
  1058. * Replace all instances of one object with another in the specified list.
  1059. * The list does not change size. An element e is replaced if
  1060. * <code>oldval == null ? e == null : oldval.equals(e)</code>.
  1061. *
  1062. * @param list the list to iterate over
  1063. * @param oldval the element to replace
  1064. * @param newval the new value for the element
  1065. * @return <code>true</code> if a replacement occurred.
  1066. * @throws UnsupportedOperationException if the list iterator does not allow
  1067. * for the set operation
  1068. * @throws ClassCastException if newval is of a type which cannot be added
  1069. * to the list
  1070. * @throws IllegalArgumentException if some other aspect of newval stops
  1071. * it being added to the list
  1072. * @since 1.4
  1073. */
  1074. public static <T> boolean replaceAll(List<T> list, T oldval, T newval)
  1075. {
  1076. ListIterator<T> itr = list.listIterator();
  1077. boolean replace_occured = false;
  1078. for (int i = list.size(); --i >= 0; )
  1079. if (AbstractCollection.equals(oldval, itr.next()))
  1080. {
  1081. itr.set(newval);
  1082. replace_occured = true;
  1083. }
  1084. return replace_occured;
  1085. }
  1086. /**
  1087. * Reverse a given list. This method works in linear time.
  1088. *
  1089. * @param l the list to reverse
  1090. * @throws UnsupportedOperationException if l.listIterator() does not
  1091. * support the set operation
  1092. */
  1093. public static void reverse(List<?> l)
  1094. {
  1095. ListIterator i1 = l.listIterator();
  1096. int pos1 = 1;
  1097. int pos2 = l.size();
  1098. ListIterator i2 = l.listIterator(pos2);
  1099. while (pos1 < pos2)
  1100. {
  1101. Object o1 = i1.next();
  1102. Object o2 = i2.previous();
  1103. i1.set(o2);
  1104. i2.set(o1);
  1105. ++pos1;
  1106. --pos2;
  1107. }
  1108. }
  1109. /**
  1110. * Get a comparator that implements the reverse of the ordering
  1111. * specified by the given Comparator. If the Comparator is null,
  1112. * this is equivalent to {@link #reverseOrder()}. The return value
  1113. * of this method is Serializable, if the specified Comparator is
  1114. * either Serializable or null.
  1115. *
  1116. * @param c the comparator to invert
  1117. * @return a comparator that imposes reverse ordering
  1118. * @see Comparable
  1119. * @see Serializable
  1120. *
  1121. * @since 1.5
  1122. */
  1123. public static <T> Comparator<T> reverseOrder(final Comparator<T> c)
  1124. {
  1125. if (c == null)
  1126. return (Comparator<T>) rcInstance;
  1127. return new ReverseComparator<T> ()
  1128. {
  1129. public int compare(T a, T b)
  1130. {
  1131. return - c.compare(a, b);
  1132. }
  1133. };
  1134. }
  1135. /**
  1136. * Get a comparator that implements the reverse of natural ordering. In
  1137. * other words, this sorts Comparable objects opposite of how their
  1138. * compareTo method would sort. This makes it easy to sort into reverse
  1139. * order, by simply passing Collections.reverseOrder() to the sort method.
  1140. * The return value of this method is Serializable.
  1141. *
  1142. * @return a comparator that imposes reverse natural ordering
  1143. * @see Comparable
  1144. * @see Serializable
  1145. */
  1146. public static <T> Comparator<T> reverseOrder()
  1147. {
  1148. return (Comparator<T>) rcInstance;
  1149. }
  1150. /**
  1151. * The object for {@link #reverseOrder()}.
  1152. */
  1153. private static final ReverseComparator rcInstance = new ReverseComparator();
  1154. /**
  1155. * The implementation of {@link #reverseOrder()}. This class name
  1156. * is required for compatibility with Sun's JDK serializability.
  1157. *
  1158. * @author Eric Blake (ebb9@email.byu.edu)
  1159. */
  1160. private static class ReverseComparator<T>
  1161. implements Comparator<T>, Serializable
  1162. {
  1163. /**
  1164. * Compatible with JDK 1.4.
  1165. */
  1166. private static final long serialVersionUID = 7207038068494060240L;
  1167. /**
  1168. * A private constructor adds overhead.
  1169. */
  1170. ReverseComparator()
  1171. {
  1172. }
  1173. /**
  1174. * Compare two objects in reverse natural order.
  1175. *
  1176. * @param a the first object
  1177. * @param b the second object
  1178. * @return &lt;, ==, or &gt; 0 according to b.compareTo(a)
  1179. */
  1180. public int compare(T a, T b)
  1181. {
  1182. return ((Comparable) b).compareTo(a);
  1183. }
  1184. }
  1185. /**
  1186. * Rotate the elements in a list by a specified distance. After calling this
  1187. * method, the element now at index <code>i</code> was formerly at index
  1188. * <code>(i - distance) mod list.size()</code>. The list size is unchanged.
  1189. * <p>
  1190. *
  1191. * For example, suppose a list contains <code>[t, a, n, k, s]</code>. After
  1192. * either <code>Collections.rotate(l, 4)</code> or
  1193. * <code>Collections.rotate(l, -1)</code>, the new contents are
  1194. * <code>[s, t, a, n, k]</code>. This can be applied to sublists to rotate
  1195. * just a portion of the list. For example, to move element <code>a</code>
  1196. * forward two positions in the original example, use
  1197. * <code>Collections.rotate(l.subList(1, 3+1), -1)</code>, which will
  1198. * result in <code>[t, n, k, a, s]</code>.
  1199. * <p>
  1200. *
  1201. * If the list is small or implements {@link RandomAccess}, the
  1202. * implementation exchanges the first element to its destination, then the
  1203. * displaced element, and so on until a circuit has been completed. The
  1204. * process is repeated if needed on the second element, and so forth, until
  1205. * all elements have been swapped. For large non-random lists, the
  1206. * implementation breaks the list into two sublists at index
  1207. * <code>-distance mod size</code>, calls {@link #reverse(List)} on the
  1208. * pieces, then reverses the overall list.
  1209. *
  1210. * @param list the list to rotate
  1211. * @param distance the distance to rotate by; unrestricted in value
  1212. * @throws UnsupportedOperationException if the list does not support set
  1213. * @since 1.4
  1214. */
  1215. public static void rotate(List<?> list, int distance)
  1216. {
  1217. int size = list.size();
  1218. if (size == 0)
  1219. return;
  1220. distance %= size;
  1221. if (distance == 0)
  1222. return;
  1223. if (distance < 0)
  1224. distance += size;
  1225. if (isSequential(list))
  1226. {
  1227. reverse(list);
  1228. reverse(list.subList(0, distance));
  1229. reverse(list.subList(distance, size));
  1230. }
  1231. else
  1232. {
  1233. // Determine the least common multiple of distance and size, as there
  1234. // are (distance / LCM) loops to cycle through.
  1235. int a = size;
  1236. int lcm = distance;
  1237. int b = a % lcm;
  1238. while (b != 0)
  1239. {
  1240. a = lcm;
  1241. lcm = b;
  1242. b = a % lcm;
  1243. }
  1244. // Now, make the swaps. We must take the remainder every time through
  1245. // the inner loop so that we don't overflow i to negative values.
  1246. List<Object> objList = (List<Object>) list;
  1247. while (--lcm >= 0)
  1248. {
  1249. Object o = objList.get(lcm);
  1250. for (int i = lcm + distance; i != lcm; i = (i + distance) % size)
  1251. o = objList.set(i, o);
  1252. objList.set(lcm, o);
  1253. }
  1254. }
  1255. }
  1256. /**
  1257. * Shuffle a list according to a default source of randomness. The algorithm
  1258. * used iterates backwards over the list, swapping each element with an
  1259. * element randomly selected from the elements in positions less than or
  1260. * equal to it (using r.nextInt(int)).
  1261. * <p>
  1262. *
  1263. * This algorithm would result in a perfectly fair shuffle (that is, each
  1264. * element would have an equal chance of ending up in any position) if r were
  1265. * a perfect source of randomness. In practice the results are merely very
  1266. * close to perfect.
  1267. * <p>
  1268. *
  1269. * This method operates in linear time. To do this on large lists which do
  1270. * not implement {@link RandomAccess}, a temporary array is used to acheive
  1271. * this speed, since it would be quadratic access otherwise.
  1272. *
  1273. * @param l the list to shuffle
  1274. * @throws UnsupportedOperationException if l.listIterator() does not
  1275. * support the set operation
  1276. */
  1277. public static void shuffle(List<?> l)
  1278. {
  1279. if (defaultRandom == null)
  1280. {
  1281. synchronized (Collections.class)
  1282. {
  1283. if (defaultRandom == null)
  1284. defaultRandom = new Random();
  1285. }
  1286. }
  1287. shuffle(l, defaultRandom);
  1288. }
  1289. /**
  1290. * Cache a single Random object for use by shuffle(List). This improves
  1291. * performance as well as ensuring that sequential calls to shuffle() will
  1292. * not result in the same shuffle order occurring: the resolution of
  1293. * System.currentTimeMillis() is not sufficient to guarantee a unique seed.
  1294. */
  1295. private static Random defaultRandom = null;
  1296. /**
  1297. * Shuffle a list according to a given source of randomness. The algorithm
  1298. * used iterates backwards over the list, swapping each element with an
  1299. * element randomly selected from the elements in positions less than or
  1300. * equal to it (using r.nextInt(int)).
  1301. * <p>
  1302. *
  1303. * This algorithm would result in a perfectly fair shuffle (that is, each
  1304. * element would have an equal chance of ending up in any position) if r were
  1305. * a perfect source of randomness. In practise (eg if r = new Random()) the
  1306. * results are merely very close to perfect.
  1307. * <p>
  1308. *
  1309. * This method operates in linear time. To do this on large lists which do
  1310. * not implement {@link RandomAccess}, a temporary array is used to acheive
  1311. * this speed, since it would be quadratic access otherwise.
  1312. *
  1313. * @param l the list to shuffle
  1314. * @param r the source of randomness to use for the shuffle
  1315. * @throws UnsupportedOperationException if l.listIterator() does not
  1316. * support the set operation
  1317. */
  1318. public static void shuffle(List<?> l, Random r)
  1319. {
  1320. int lsize = l.size();
  1321. List<Object> list = (List<Object>) l;
  1322. ListIterator<Object> i = list.listIterator(lsize);
  1323. boolean sequential = isSequential(l);
  1324. Object[] a = null; // stores a copy of the list for the sequential case
  1325. if (sequential)
  1326. a = list.toArray();
  1327. for (int pos = lsize - 1; pos > 0; --pos)
  1328. {
  1329. // Obtain a random position to swap with. pos + 1 is used so that the
  1330. // range of the random number includes the current position.
  1331. int swap = r.nextInt(pos + 1);
  1332. // Swap the desired element.
  1333. Object o;
  1334. if (sequential)
  1335. {
  1336. o = a[swap];
  1337. a[swap] = i.previous();
  1338. }
  1339. else
  1340. o = list.set(swap, i.previous());
  1341. i.set(o);
  1342. }
  1343. }
  1344. /**
  1345. * Returns the frequency of the specified object within the supplied
  1346. * collection. The frequency represents the number of occurrences of
  1347. * elements within the collection which return <code>true</code> when
  1348. * compared with the object using the <code>equals</code> method.
  1349. *
  1350. * @param c the collection to scan for occurrences of the object.
  1351. * @param o the object to locate occurrances of within the collection.
  1352. * @throws NullPointerException if the collection is <code>null</code>.
  1353. * @since 1.5
  1354. */
  1355. public static int frequency (Collection<?> c, Object o)
  1356. {
  1357. int result = 0;
  1358. final Iterator<?> it = c.iterator();
  1359. while (it.hasNext())
  1360. {
  1361. Object v = it.next();
  1362. if (AbstractCollection.equals(o, v))
  1363. ++result;
  1364. }
  1365. return result;
  1366. }
  1367. /**
  1368. * Adds all the specified elements to the given collection, in a similar
  1369. * way to the <code>addAll</code> method of the <code>Collection</code>.
  1370. * However, this is a variable argument method which allows the new elements
  1371. * to be specified individually or in array form, as opposed to the list
  1372. * required by the collection's <code>addAll</code> method. This has
  1373. * benefits in both simplicity (multiple elements can be added without
  1374. * having to be wrapped inside a grouping structure) and efficiency
  1375. * (as a redundant list doesn't have to be created to add an individual
  1376. * set of elements or an array).
  1377. *
  1378. * @param c the collection to which the elements should be added.
  1379. * @param a the elements to be added to the collection.
  1380. * @return true if the collection changed its contents as a result.
  1381. * @throws UnsupportedOperationException if the collection does not support
  1382. * addition.
  1383. * @throws NullPointerException if one or more elements in a are null,
  1384. * and the collection does not allow null
  1385. * elements. This exception is also thrown
  1386. * if either <code>c</code> or <code>a</code>
  1387. * are null.
  1388. * @throws IllegalArgumentException if the collection won't allow an element
  1389. * to be added for some other reason.
  1390. * @since 1.5
  1391. */
  1392. public static <T> boolean addAll(Collection<? super T> c, T... a)
  1393. {
  1394. boolean overall = false;
  1395. for (T element : a)
  1396. {
  1397. boolean result = c.add(element);
  1398. if (result)
  1399. overall = true;
  1400. }
  1401. return overall;
  1402. }
  1403. /**
  1404. * Returns true if the two specified collections have no elements in
  1405. * common. This method may give unusual results if one or both collections
  1406. * use a non-standard equality test. In the trivial case of comparing
  1407. * a collection with itself, this method returns true if, and only if,
  1408. * the collection is empty.
  1409. *
  1410. * @param c1 the first collection to compare.
  1411. * @param c2 the second collection to compare.
  1412. * @return true if the collections are disjoint.
  1413. * @throws NullPointerException if either collection is null.
  1414. * @since 1.5
  1415. */
  1416. public static boolean disjoint(Collection<?> c1, Collection<?> c2)
  1417. {
  1418. Collection<Object> oc1 = (Collection<Object>) c1;
  1419. final Iterator<Object> it = oc1.iterator();
  1420. while (it.hasNext())
  1421. if (c2.contains(it.next()))
  1422. return false;
  1423. return true;
  1424. }
  1425. /**
  1426. * Obtain an immutable Set consisting of a single element. The return value
  1427. * of this method is Serializable.
  1428. *
  1429. * @param o the single element
  1430. * @return an immutable Set containing only o
  1431. * @see Serializable
  1432. */
  1433. public static <T> Set<T> singleton(T o)
  1434. {
  1435. return new SingletonSet<T>(o);
  1436. }
  1437. /**
  1438. * The implementation of {@link #singleton(Object)}. This class name
  1439. * is required for compatibility with Sun's JDK serializability.
  1440. *
  1441. * @author Eric Blake (ebb9@email.byu.edu)
  1442. */
  1443. private static final class SingletonSet<T> extends AbstractSet<T>
  1444. implements Serializable
  1445. {
  1446. /**
  1447. * Compatible with JDK 1.4.
  1448. */
  1449. private static final long serialVersionUID = 3193687207550431679L;
  1450. /**
  1451. * The single element; package visible for use in nested class.
  1452. * @serial the singleton
  1453. */
  1454. final T element;
  1455. /**
  1456. * Construct a singleton.
  1457. * @param o the element
  1458. */
  1459. SingletonSet(T o)
  1460. {
  1461. element = o;
  1462. }
  1463. /**
  1464. * The size: always 1!
  1465. * @return 1.
  1466. */
  1467. public int size()
  1468. {
  1469. return 1;
  1470. }
  1471. /**
  1472. * Returns an iterator over the lone element.
  1473. */
  1474. public Iterator<T> iterator()
  1475. {
  1476. return new Iterator<T>()
  1477. {
  1478. /**
  1479. * Flag to indicate whether or not the element has
  1480. * been retrieved.
  1481. */
  1482. private boolean hasNext = true;
  1483. /**
  1484. * Returns <code>true</code> if elements still remain to be
  1485. * iterated through.
  1486. *
  1487. * @return <code>true</code> if the element has not yet been returned.
  1488. */
  1489. public boolean hasNext()
  1490. {
  1491. return hasNext;
  1492. }
  1493. /**
  1494. * Returns the element.
  1495. *
  1496. * @return The element used by this singleton.
  1497. * @throws NoSuchElementException if the object
  1498. * has already been retrieved.
  1499. */
  1500. public T next()
  1501. {
  1502. if (hasNext)
  1503. {
  1504. hasNext = false;
  1505. return element;
  1506. }
  1507. else
  1508. throw new NoSuchElementException();
  1509. }
  1510. /**
  1511. * Removes the element from the singleton.
  1512. * As this set is immutable, this will always
  1513. * throw an exception.
  1514. *
  1515. * @throws UnsupportedOperationException as the
  1516. * singleton set doesn't support
  1517. * <code>remove()</code>.
  1518. */
  1519. public void remove()
  1520. {
  1521. throw new UnsupportedOperationException();
  1522. }
  1523. };
  1524. }
  1525. // The remaining methods are optional, but provide a performance
  1526. // advantage by not allocating unnecessary iterators in AbstractSet.
  1527. /**
  1528. * The set only contains one element.
  1529. *
  1530. * @param o The object to search for.
  1531. * @return <code>true</code> if o == the element of the singleton.
  1532. */
  1533. public boolean contains(Object o)
  1534. {
  1535. return equals(o, element);
  1536. }
  1537. /**
  1538. * This is true if the other collection only contains the element.
  1539. *
  1540. * @param c A collection to compare against this singleton.
  1541. * @return <code>true</code> if c only contains either no elements or
  1542. * elements equal to the element in this singleton.
  1543. */
  1544. public boolean containsAll(Collection<?> c)
  1545. {
  1546. Iterator<?> i = c.iterator();
  1547. int pos = c.size();
  1548. while (--pos >= 0)
  1549. if (! equals(i.next(), element))
  1550. return false;
  1551. return true;
  1552. }
  1553. /**
  1554. * The hash is just that of the element.
  1555. *
  1556. * @return The hashcode of the element.
  1557. */
  1558. public int hashCode()
  1559. {
  1560. return hashCode(element);
  1561. }
  1562. /**
  1563. * Returning an array is simple.
  1564. *
  1565. * @return An array containing the element.
  1566. */
  1567. public Object[] toArray()
  1568. {
  1569. return new Object[] {element};
  1570. }
  1571. /**
  1572. * Obvious string.
  1573. *
  1574. * @return The string surrounded by enclosing
  1575. * square brackets.
  1576. */
  1577. public String toString()
  1578. {
  1579. return "[" + element + "]";
  1580. }
  1581. } // class SingletonSet
  1582. /**
  1583. * Obtain an immutable List consisting of a single element. The return value
  1584. * of this method is Serializable, and implements RandomAccess.
  1585. *
  1586. * @param o the single element
  1587. * @return an immutable List containing only o
  1588. * @see Serializable
  1589. * @see RandomAccess
  1590. * @since 1.3
  1591. */
  1592. public static <T> List<T> singletonList(T o)
  1593. {
  1594. return new SingletonList<T>(o);
  1595. }
  1596. /**
  1597. * The implementation of {@link #singletonList(Object)}. This class name
  1598. * is required for compatibility with Sun's JDK serializability.
  1599. *
  1600. * @author Eric Blake (ebb9@email.byu.edu)
  1601. */
  1602. private static final class SingletonList<T> extends AbstractList<T>
  1603. implements Serializable, RandomAccess
  1604. {
  1605. /**
  1606. * Compatible with JDK 1.4.
  1607. */
  1608. private static final long serialVersionUID = 3093736618740652951L;
  1609. /**
  1610. * The single element.
  1611. * @serial the singleton
  1612. */
  1613. private final T element;
  1614. /**
  1615. * Construct a singleton.
  1616. * @param o the element
  1617. */
  1618. SingletonList(T o)
  1619. {
  1620. element = o;
  1621. }
  1622. /**
  1623. * The size: always 1!
  1624. * @return 1.
  1625. */
  1626. public int size()
  1627. {
  1628. return 1;
  1629. }
  1630. /**
  1631. * Only index 0 is valid.
  1632. * @param index The index of the element
  1633. * to retrieve.
  1634. * @return The singleton's element if the
  1635. * index is 0.
  1636. * @throws IndexOutOfBoundsException if
  1637. * index is not 0.
  1638. */
  1639. public T get(int index)
  1640. {
  1641. if (index == 0)
  1642. return element;
  1643. throw new IndexOutOfBoundsException();
  1644. }
  1645. // The remaining methods are optional, but provide a performance
  1646. // advantage by not allocating unnecessary iterators in AbstractList.
  1647. /**
  1648. * The set only contains one element.
  1649. *
  1650. * @param o The object to search for.
  1651. * @return <code>true</code> if o == the singleton element.
  1652. */
  1653. public boolean contains(Object o)
  1654. {
  1655. return equals(o, element);
  1656. }
  1657. /**
  1658. * This is true if the other collection only contains the element.
  1659. *
  1660. * @param c A collection to compare against this singleton.
  1661. * @return <code>true</code> if c only contains either no elements or
  1662. * elements equal to the element in this singleton.
  1663. */
  1664. public boolean containsAll(Collection<?> c)
  1665. {
  1666. Iterator<?> i = c.iterator();
  1667. int pos = c.size();
  1668. while (--pos >= 0)
  1669. if (! equals(i.next(), element))
  1670. return false;
  1671. return true;
  1672. }
  1673. /**
  1674. * Speed up the hashcode computation.
  1675. *
  1676. * @return The hashcode of the list, based
  1677. * on the hashcode of the singleton element.
  1678. */
  1679. public int hashCode()
  1680. {
  1681. return 31 + hashCode(element);
  1682. }
  1683. /**
  1684. * Either the list has it or not.
  1685. *
  1686. * @param o The object to find the first index of.
  1687. * @return 0 if o is the singleton element, -1 if not.
  1688. */
  1689. public int indexOf(Object o)
  1690. {
  1691. return equals(o, element) ? 0 : -1;
  1692. }
  1693. /**
  1694. * Either the list has it or not.
  1695. *
  1696. * @param o The object to find the last index of.
  1697. * @return 0 if o is the singleton element, -1 if not.
  1698. */
  1699. public int lastIndexOf(Object o)
  1700. {
  1701. return equals(o, element) ? 0 : -1;
  1702. }
  1703. /**
  1704. * Sublists are limited in scope.
  1705. *
  1706. * @param from The starting bound for the sublist.
  1707. * @param to The ending bound for the sublist.
  1708. * @return Either an empty list if both bounds are
  1709. * 0 or 1, or this list if the bounds are 0 and 1.
  1710. * @throws IllegalArgumentException if <code>from > to</code>
  1711. * @throws IndexOutOfBoundsException if either bound is greater
  1712. * than 1.
  1713. */
  1714. public List<T> subList(int from, int to)
  1715. {
  1716. if (from == to && (to == 0 || to == 1))
  1717. return emptyList();
  1718. if (from == 0 && to == 1)
  1719. return this;
  1720. if (from > to)
  1721. throw new IllegalArgumentException();
  1722. throw new IndexOutOfBoundsException();
  1723. }
  1724. /**
  1725. * Returning an array is simple.
  1726. *
  1727. * @return An array containing the element.
  1728. */
  1729. public Object[] toArray()
  1730. {
  1731. return new Object[] {element};
  1732. }
  1733. /**
  1734. * Obvious string.
  1735. *
  1736. * @return The string surrounded by enclosing
  1737. * square brackets.
  1738. */
  1739. public String toString()
  1740. {
  1741. return "[" + element + "]";
  1742. }
  1743. } // class SingletonList
  1744. /**
  1745. * Obtain an immutable Map consisting of a single key-value pair.
  1746. * The return value of this method is Serializable.
  1747. *
  1748. * @param key the single key
  1749. * @param value the single value
  1750. * @return an immutable Map containing only the single key-value pair
  1751. * @see Serializable
  1752. * @since 1.3
  1753. */
  1754. public static <K, V> Map<K, V> singletonMap(K key, V value)
  1755. {
  1756. return new SingletonMap<K, V>(key, value);
  1757. }
  1758. /**
  1759. * The implementation of {@link #singletonMap(Object, Object)}. This class
  1760. * name is required for compatibility with Sun's JDK serializability.
  1761. *
  1762. * @author Eric Blake (ebb9@email.byu.edu)
  1763. */
  1764. private static final class SingletonMap<K, V> extends AbstractMap<K, V>
  1765. implements Serializable
  1766. {
  1767. /**
  1768. * Compatible with JDK 1.4.
  1769. */
  1770. private static final long serialVersionUID = -6979724477215052911L;
  1771. /**
  1772. * The single key.
  1773. * @serial the singleton key
  1774. */
  1775. private final K k;
  1776. /**
  1777. * The corresponding value.
  1778. * @serial the singleton value
  1779. */
  1780. private final V v;
  1781. /**
  1782. * Cache the entry set.
  1783. */
  1784. private transient Set<Map.Entry<K, V>> entries;
  1785. /**
  1786. * Construct a singleton.
  1787. * @param key the key
  1788. * @param value the value
  1789. */
  1790. SingletonMap(K key, V value)
  1791. {
  1792. k = key;
  1793. v = value;
  1794. }
  1795. /**
  1796. * There is a single immutable entry.
  1797. *
  1798. * @return A singleton containing the map entry.
  1799. */
  1800. public Set<Map.Entry<K, V>> entrySet()
  1801. {
  1802. if (entries == null)
  1803. {
  1804. Map.Entry<K,V> entry = new AbstractMap.SimpleEntry<K, V>(k, v)
  1805. {
  1806. /**
  1807. * Sets the value of the map entry to the supplied value.
  1808. * An exception is always thrown, as the map is immutable.
  1809. *
  1810. * @param o The new value.
  1811. * @return The old value.
  1812. * @throws UnsupportedOperationException as setting the value
  1813. * is not supported.
  1814. */
  1815. public V setValue(V o)
  1816. {
  1817. throw new UnsupportedOperationException();
  1818. }
  1819. };
  1820. entries = singleton(entry);
  1821. }
  1822. return entries;
  1823. }
  1824. // The remaining methods are optional, but provide a performance
  1825. // advantage by not allocating unnecessary iterators in AbstractMap.
  1826. /**
  1827. * Single entry.
  1828. *
  1829. * @param key The key to look for.
  1830. * @return <code>true</code> if the key is the same as the one used by
  1831. * this map.
  1832. */
  1833. public boolean containsKey(Object key)
  1834. {
  1835. return equals(key, k);
  1836. }
  1837. /**
  1838. * Single entry.
  1839. *
  1840. * @param value The value to look for.
  1841. * @return <code>true</code> if the value is the same as the one used by
  1842. * this map.
  1843. */
  1844. public boolean containsValue(Object value)
  1845. {
  1846. return equals(value, v);
  1847. }
  1848. /**
  1849. * Single entry.
  1850. *
  1851. * @param key The key of the value to be retrieved.
  1852. * @return The singleton value if the key is the same as the
  1853. * singleton key, null otherwise.
  1854. */
  1855. public V get(Object key)
  1856. {
  1857. return equals(key, k) ? v : null;
  1858. }
  1859. /**
  1860. * Calculate the hashcode directly.
  1861. *
  1862. * @return The hashcode computed from the singleton key
  1863. * and the singleton value.
  1864. */
  1865. public int hashCode()
  1866. {
  1867. return hashCode(k) ^ hashCode(v);
  1868. }
  1869. /**
  1870. * Return the keyset.
  1871. *
  1872. * @return A singleton containing the key.
  1873. */
  1874. public Set<K> keySet()
  1875. {
  1876. if (keys == null)
  1877. keys = singleton(k);
  1878. return keys;
  1879. }
  1880. /**
  1881. * The size: always 1!
  1882. *
  1883. * @return 1.
  1884. */
  1885. public int size()
  1886. {
  1887. return 1;
  1888. }
  1889. /**
  1890. * Return the values. Technically, a singleton, while more specific than
  1891. * a general Collection, will work. Besides, that's what the JDK uses!
  1892. *
  1893. * @return A singleton containing the value.
  1894. */
  1895. public Collection<V> values()
  1896. {
  1897. if (values == null)
  1898. values = singleton(v);
  1899. return values;
  1900. }
  1901. /**
  1902. * Obvious string.
  1903. *
  1904. * @return A string containing the string representations of the key
  1905. * and its associated value.
  1906. */
  1907. public String toString()
  1908. {
  1909. return "{" + k + "=" + v + "}";
  1910. }
  1911. } // class SingletonMap
  1912. /**
  1913. * Sort a list according to the natural ordering of its elements. The list
  1914. * must be modifiable, but can be of fixed size. The sort algorithm is
  1915. * precisely that used by Arrays.sort(Object[]), which offers guaranteed
  1916. * nlog(n) performance. This implementation dumps the list into an array,
  1917. * sorts the array, and then iterates over the list setting each element from
  1918. * the array.
  1919. *
  1920. * @param l the List to sort (<code>null</code> not permitted)
  1921. * @throws ClassCastException if some items are not mutually comparable
  1922. * @throws UnsupportedOperationException if the List is not modifiable
  1923. * @throws NullPointerException if the list is <code>null</code>, or contains
  1924. * some element that is <code>null</code>.
  1925. * @see Arrays#sort(Object[])
  1926. */
  1927. public static <T extends Comparable<? super T>> void sort(List<T> l)
  1928. {
  1929. sort(l, null);
  1930. }
  1931. /**
  1932. * Sort a list according to a specified Comparator. The list must be
  1933. * modifiable, but can be of fixed size. The sort algorithm is precisely that
  1934. * used by Arrays.sort(Object[], Comparator), which offers guaranteed
  1935. * nlog(n) performance. This implementation dumps the list into an array,
  1936. * sorts the array, and then iterates over the list setting each element from
  1937. * the array.
  1938. *
  1939. * @param l the List to sort (<code>null</code> not permitted)
  1940. * @param c the Comparator specifying the ordering for the elements, or
  1941. * <code>null</code> for natural ordering
  1942. * @throws ClassCastException if c will not compare some pair of items
  1943. * @throws UnsupportedOperationException if the List is not modifiable
  1944. * @throws NullPointerException if the List is <code>null</code> or
  1945. * <code>null</code> is compared by natural ordering (only possible
  1946. * when c is <code>null</code>)
  1947. *
  1948. * @see Arrays#sort(Object[], Comparator)
  1949. */
  1950. public static <T> void sort(List<T> l, Comparator<? super T> c)
  1951. {
  1952. T[] a = (T[]) l.toArray();
  1953. Arrays.sort(a, c);
  1954. ListIterator<T> i = l.listIterator();
  1955. for (int pos = 0, alen = a.length; pos < alen; pos++)
  1956. {
  1957. i.next();
  1958. i.set(a[pos]);
  1959. }
  1960. }
  1961. /**
  1962. * Swaps the elements at the specified positions within the list. Equal
  1963. * positions have no effect.
  1964. *
  1965. * @param l the list to work on
  1966. * @param i the first index to swap
  1967. * @param j the second index
  1968. * @throws UnsupportedOperationException if list.set is not supported
  1969. * @throws IndexOutOfBoundsException if either i or j is &lt; 0 or &gt;=
  1970. * list.size()
  1971. * @since 1.4
  1972. */
  1973. public static void swap(List<?> l, int i, int j)
  1974. {
  1975. List<Object> list = (List<Object>) l;
  1976. list.set(i, list.set(j, list.get(i)));
  1977. }
  1978. /**
  1979. * Returns a synchronized (thread-safe) collection wrapper backed by the
  1980. * given collection. Notice that element access through the iterators
  1981. * is thread-safe, but if the collection can be structurally modified
  1982. * (adding or removing elements) then you should synchronize around the
  1983. * iteration to avoid non-deterministic behavior:<br>
  1984. * <pre>
  1985. * Collection c = Collections.synchronizedCollection(new Collection(...));
  1986. * ...
  1987. * synchronized (c)
  1988. * {
  1989. * Iterator i = c.iterator();
  1990. * while (i.hasNext())
  1991. * foo(i.next());
  1992. * }
  1993. * </pre><p>
  1994. *
  1995. * Since the collection might be a List or a Set, and those have incompatible
  1996. * equals and hashCode requirements, this relies on Object's implementation
  1997. * rather than passing those calls on to the wrapped collection. The returned
  1998. * Collection implements Serializable, but can only be serialized if
  1999. * the collection it wraps is likewise Serializable.
  2000. *
  2001. * @param c the collection to wrap
  2002. * @return a synchronized view of the collection
  2003. * @see Serializable
  2004. */
  2005. public static <T> Collection<T> synchronizedCollection(Collection<T> c)
  2006. {
  2007. return new SynchronizedCollection<T>(c);
  2008. }
  2009. /**
  2010. * The implementation of {@link #synchronizedCollection(Collection)}. This
  2011. * class name is required for compatibility with Sun's JDK serializability.
  2012. * Package visible, so that collections such as the one for
  2013. * Hashtable.values() can specify which object to synchronize on.
  2014. *
  2015. * @author Eric Blake (ebb9@email.byu.edu)
  2016. */
  2017. static class SynchronizedCollection<T>
  2018. implements Collection<T>, Serializable
  2019. {
  2020. /**
  2021. * Compatible with JDK 1.4.
  2022. */
  2023. private static final long serialVersionUID = 3053995032091335093L;
  2024. /**
  2025. * The wrapped collection. Package visible for use by subclasses.
  2026. * @serial the real collection
  2027. */
  2028. final Collection<T> c;
  2029. /**
  2030. * The object to synchronize on. When an instance is created via public
  2031. * methods, it will be this; but other uses like SynchronizedMap.values()
  2032. * must specify another mutex. Package visible for use by subclasses.
  2033. * @serial the lock
  2034. */
  2035. final Object mutex;
  2036. /**
  2037. * Wrap a given collection.
  2038. * @param c the collection to wrap
  2039. * @throws NullPointerException if c is null
  2040. */
  2041. SynchronizedCollection(Collection<T> c)
  2042. {
  2043. this.c = c;
  2044. mutex = this;
  2045. if (c == null)
  2046. throw new NullPointerException();
  2047. }
  2048. /**
  2049. * Called only by trusted code to specify the mutex as well as the
  2050. * collection.
  2051. * @param sync the mutex
  2052. * @param c the collection
  2053. */
  2054. SynchronizedCollection(Object sync, Collection<T> c)
  2055. {
  2056. this.c = c;
  2057. mutex = sync;
  2058. }
  2059. /**
  2060. * Adds the object to the underlying collection, first
  2061. * obtaining a lock on the mutex.
  2062. *
  2063. * @param o The object to add.
  2064. * @return <code>true</code> if the collection was modified as a result
  2065. * of this action.
  2066. * @throws UnsupportedOperationException if this collection does not
  2067. * support the add operation.
  2068. * @throws ClassCastException if o cannot be added to this collection due
  2069. * to its type.
  2070. * @throws NullPointerException if o is null and this collection doesn't
  2071. * support the addition of null values.
  2072. * @throws IllegalArgumentException if o cannot be added to this
  2073. * collection for some other reason.
  2074. */
  2075. public boolean add(T o)
  2076. {
  2077. synchronized (mutex)
  2078. {
  2079. return c.add(o);
  2080. }
  2081. }
  2082. /**
  2083. * Adds the objects in col to the underlying collection, first
  2084. * obtaining a lock on the mutex.
  2085. *
  2086. * @param col The collection to take the new objects from.
  2087. * @return <code>true</code> if the collection was modified as a result
  2088. * of this action.
  2089. * @throws UnsupportedOperationException if this collection does not
  2090. * support the addAll operation.
  2091. * @throws ClassCastException if some element of col cannot be added to this
  2092. * collection due to its type.
  2093. * @throws NullPointerException if some element of col is null and this
  2094. * collection does not support the addition of null values.
  2095. * @throws NullPointerException if col itself is null.
  2096. * @throws IllegalArgumentException if some element of col cannot be added
  2097. * to this collection for some other reason.
  2098. */
  2099. public boolean addAll(Collection<? extends T> col)
  2100. {
  2101. synchronized (mutex)
  2102. {
  2103. return c.addAll(col);
  2104. }
  2105. }
  2106. /**
  2107. * Removes all objects from the underlying collection,
  2108. * first obtaining a lock on the mutex.
  2109. *
  2110. * @throws UnsupportedOperationException if this collection does not
  2111. * support the clear operation.
  2112. */
  2113. public void clear()
  2114. {
  2115. synchronized (mutex)
  2116. {
  2117. c.clear();
  2118. }
  2119. }
  2120. /**
  2121. * Checks for the existence of o within the underlying
  2122. * collection, first obtaining a lock on the mutex.
  2123. *
  2124. * @param o the element to look for.
  2125. * @return <code>true</code> if this collection contains at least one
  2126. * element e such that <code>o == null ? e == null : o.equals(e)</code>.
  2127. * @throws ClassCastException if the type of o is not a valid type for this
  2128. * collection.
  2129. * @throws NullPointerException if o is null and this collection doesn't
  2130. * support null values.
  2131. */
  2132. public boolean contains(Object o)
  2133. {
  2134. synchronized (mutex)
  2135. {
  2136. return c.contains(o);
  2137. }
  2138. }
  2139. /**
  2140. * Checks for the existence of each object in cl
  2141. * within the underlying collection, first obtaining
  2142. * a lock on the mutex.
  2143. *
  2144. * @param c1 the collection to test for.
  2145. * @return <code>true</code> if for every element o in c, contains(o)
  2146. * would return <code>true</code>.
  2147. * @throws ClassCastException if the type of any element in cl is not a valid
  2148. * type for this collection.
  2149. * @throws NullPointerException if some element of cl is null and this
  2150. * collection does not support null values.
  2151. * @throws NullPointerException if cl itself is null.
  2152. */
  2153. public boolean containsAll(Collection<?> c1)
  2154. {
  2155. synchronized (mutex)
  2156. {
  2157. return c.containsAll(c1);
  2158. }
  2159. }
  2160. /**
  2161. * Returns <code>true</code> if there are no objects in the underlying
  2162. * collection. A lock on the mutex is obtained before the
  2163. * check is performed.
  2164. *
  2165. * @return <code>true</code> if this collection contains no elements.
  2166. */
  2167. public boolean isEmpty()
  2168. {
  2169. synchronized (mutex)
  2170. {
  2171. return c.isEmpty();
  2172. }
  2173. }
  2174. /**
  2175. * Returns a synchronized iterator wrapper around the underlying
  2176. * collection's iterator. A lock on the mutex is obtained before
  2177. * retrieving the collection's iterator.
  2178. *
  2179. * @return An iterator over the elements in the underlying collection,
  2180. * which returns each element in any order.
  2181. */
  2182. public Iterator<T> iterator()
  2183. {
  2184. synchronized (mutex)
  2185. {
  2186. return new SynchronizedIterator<T>(mutex, c.iterator());
  2187. }
  2188. }
  2189. /**
  2190. * Removes the specified object from the underlying collection,
  2191. * first obtaining a lock on the mutex.
  2192. *
  2193. * @param o The object to remove.
  2194. * @return <code>true</code> if the collection changed as a result of this call, that is,
  2195. * if the collection contained at least one occurrence of o.
  2196. * @throws UnsupportedOperationException if this collection does not
  2197. * support the remove operation.
  2198. * @throws ClassCastException if the type of o is not a valid type
  2199. * for this collection.
  2200. * @throws NullPointerException if o is null and the collection doesn't
  2201. * support null values.
  2202. */
  2203. public boolean remove(Object o)
  2204. {
  2205. synchronized (mutex)
  2206. {
  2207. return c.remove(o);
  2208. }
  2209. }
  2210. /**
  2211. * Removes all elements, e, of the underlying
  2212. * collection for which <code>col.contains(e)</code>
  2213. * returns <code>true</code>. A lock on the mutex is obtained
  2214. * before the operation proceeds.
  2215. *
  2216. * @param col The collection of objects to be removed.
  2217. * @return <code>true</code> if this collection was modified as a result of this call.
  2218. * @throws UnsupportedOperationException if this collection does not
  2219. * support the removeAll operation.
  2220. * @throws ClassCastException if the type of any element in c is not a valid
  2221. * type for this collection.
  2222. * @throws NullPointerException if some element of c is null and this
  2223. * collection does not support removing null values.
  2224. * @throws NullPointerException if c itself is null.
  2225. */
  2226. public boolean removeAll(Collection<?> col)
  2227. {
  2228. synchronized (mutex)
  2229. {
  2230. return c.removeAll(col);
  2231. }
  2232. }
  2233. /**
  2234. * Retains all elements, e, of the underlying
  2235. * collection for which <code>col.contains(e)</code>
  2236. * returns <code>true</code>. That is, every element that doesn't
  2237. * exist in col is removed. A lock on the mutex is obtained
  2238. * before the operation proceeds.
  2239. *
  2240. * @param col The collection of objects to be removed.
  2241. * @return <code>true</code> if this collection was modified as a result of this call.
  2242. * @throws UnsupportedOperationException if this collection does not
  2243. * support the removeAll operation.
  2244. * @throws ClassCastException if the type of any element in c is not a valid
  2245. * type for this collection.
  2246. * @throws NullPointerException if some element of c is null and this
  2247. * collection does not support removing null values.
  2248. * @throws NullPointerException if c itself is null.
  2249. */
  2250. public boolean retainAll(Collection<?> col)
  2251. {
  2252. synchronized (mutex)
  2253. {
  2254. return c.retainAll(col);
  2255. }
  2256. }
  2257. /**
  2258. * Retrieves the size of the underlying collection.
  2259. * A lock on the mutex is obtained before the collection
  2260. * is accessed.
  2261. *
  2262. * @return The size of the collection.
  2263. */
  2264. public int size()
  2265. {
  2266. synchronized (mutex)
  2267. {
  2268. return c.size();
  2269. }
  2270. }
  2271. /**
  2272. * Returns an array containing each object within the underlying
  2273. * collection. A lock is obtained on the mutex before the collection
  2274. * is accessed.
  2275. *
  2276. * @return An array of objects, matching the collection in size. The
  2277. * elements occur in any order.
  2278. */
  2279. public Object[] toArray()
  2280. {
  2281. synchronized (mutex)
  2282. {
  2283. return c.toArray();
  2284. }
  2285. }
  2286. /**
  2287. * Copies the elements in the underlying collection to the supplied
  2288. * array. If <code>a.length < size()</code>, a new array of the
  2289. * same run-time type is created, with a size equal to that of
  2290. * the collection. If <code>a.length > size()</code>, then the
  2291. * elements from 0 to <code>size() - 1</code> contain the elements
  2292. * from this collection. The following element is set to null
  2293. * to indicate the end of the collection objects. However, this
  2294. * only makes a difference if null is not a permitted value within
  2295. * the collection.
  2296. * Before the copying takes place, a lock is obtained on the mutex.
  2297. *
  2298. * @param a An array to copy elements to.
  2299. * @return An array containing the elements of the underlying collection.
  2300. * @throws ArrayStoreException if the type of any element of the
  2301. * collection is not a subtype of the element type of a.
  2302. */
  2303. public <E> E[] toArray(E[] a)
  2304. {
  2305. synchronized (mutex)
  2306. {
  2307. return c.toArray(a);
  2308. }
  2309. }
  2310. /**
  2311. * Returns a string representation of the underlying collection.
  2312. * A lock is obtained on the mutex before the string is created.
  2313. *
  2314. * @return A string representation of the collection.
  2315. */
  2316. public String toString()
  2317. {
  2318. synchronized (mutex)
  2319. {
  2320. return c.toString();
  2321. }
  2322. }
  2323. } // class SynchronizedCollection
  2324. /**
  2325. * The implementation of the various iterator methods in the
  2326. * synchronized classes. These iterators must "sync" on the same object
  2327. * as the collection they iterate over.
  2328. *
  2329. * @author Eric Blake (ebb9@email.byu.edu)
  2330. */
  2331. private static class SynchronizedIterator<T> implements Iterator<T>
  2332. {
  2333. /**
  2334. * The object to synchronize on. Package visible for use by subclass.
  2335. */
  2336. final Object mutex;
  2337. /**
  2338. * The wrapped iterator.
  2339. */
  2340. private final Iterator<T> i;
  2341. /**
  2342. * Only trusted code creates a wrapper, with the specified sync.
  2343. * @param sync the mutex
  2344. * @param i the wrapped iterator
  2345. */
  2346. SynchronizedIterator(Object sync, Iterator<T> i)
  2347. {
  2348. this.i = i;
  2349. mutex = sync;
  2350. }
  2351. /**
  2352. * Retrieves the next object in the underlying collection.
  2353. * A lock is obtained on the mutex before the collection is accessed.
  2354. *
  2355. * @return The next object in the collection.
  2356. * @throws NoSuchElementException if there are no more elements
  2357. */
  2358. public T next()
  2359. {
  2360. synchronized (mutex)
  2361. {
  2362. return i.next();
  2363. }
  2364. }
  2365. /**
  2366. * Returns <code>true</code> if objects can still be retrieved from the iterator
  2367. * using <code>next()</code>. A lock is obtained on the mutex before
  2368. * the collection is accessed.
  2369. *
  2370. * @return <code>true</code> if at least one element is still to be returned by
  2371. * <code>next()</code>.
  2372. */
  2373. public boolean hasNext()
  2374. {
  2375. synchronized (mutex)
  2376. {
  2377. return i.hasNext();
  2378. }
  2379. }
  2380. /**
  2381. * Removes the object that was last returned by <code>next()</code>
  2382. * from the underlying collection. Only one call to this method is
  2383. * allowed per call to the <code>next()</code> method, and it does
  2384. * not affect the value that will be returned by <code>next()</code>.
  2385. * Thus, if element n was retrieved from the collection by
  2386. * <code>next()</code>, it is this element that gets removed.
  2387. * Regardless of whether this takes place or not, element n+1 is
  2388. * still returned on the subsequent <code>next()</code> call.
  2389. *
  2390. * @throws IllegalStateException if next has not yet been called or remove
  2391. * has already been called since the last call to next.
  2392. * @throws UnsupportedOperationException if this Iterator does not support
  2393. * the remove operation.
  2394. */
  2395. public void remove()
  2396. {
  2397. synchronized (mutex)
  2398. {
  2399. i.remove();
  2400. }
  2401. }
  2402. } // class SynchronizedIterator
  2403. /**
  2404. * Returns a synchronized (thread-safe) list wrapper backed by the
  2405. * given list. Notice that element access through the iterators
  2406. * is thread-safe, but if the list can be structurally modified
  2407. * (adding or removing elements) then you should synchronize around the
  2408. * iteration to avoid non-deterministic behavior:<br>
  2409. * <pre>
  2410. * List l = Collections.synchronizedList(new List(...));
  2411. * ...
  2412. * synchronized (l)
  2413. * {
  2414. * Iterator i = l.iterator();
  2415. * while (i.hasNext())
  2416. * foo(i.next());
  2417. * }
  2418. * </pre><p>
  2419. *
  2420. * The returned List implements Serializable, but can only be serialized if
  2421. * the list it wraps is likewise Serializable. In addition, if the wrapped
  2422. * list implements RandomAccess, this does too.
  2423. *
  2424. * @param l the list to wrap
  2425. * @return a synchronized view of the list
  2426. * @see Serializable
  2427. * @see RandomAccess
  2428. */
  2429. public static <T> List<T> synchronizedList(List<T> l)
  2430. {
  2431. if (l instanceof RandomAccess)
  2432. return new SynchronizedRandomAccessList<T>(l);
  2433. return new SynchronizedList<T>(l);
  2434. }
  2435. /**
  2436. * The implementation of {@link #synchronizedList(List)} for sequential
  2437. * lists. This class name is required for compatibility with Sun's JDK
  2438. * serializability. Package visible, so that lists such as Vector.subList()
  2439. * can specify which object to synchronize on.
  2440. *
  2441. * @author Eric Blake (ebb9@email.byu.edu)
  2442. */
  2443. static class SynchronizedList<T> extends SynchronizedCollection<T>
  2444. implements List<T>
  2445. {
  2446. /**
  2447. * Compatible with JDK 1.4.
  2448. */
  2449. private static final long serialVersionUID = -7754090372962971524L;
  2450. /**
  2451. * The wrapped list; stored both here and in the superclass to avoid
  2452. * excessive casting. Package visible for use by subclass.
  2453. * @serial the wrapped list
  2454. */
  2455. final List<T> list;
  2456. /**
  2457. * Wrap a given list.
  2458. * @param l the list to wrap
  2459. * @throws NullPointerException if l is null
  2460. */
  2461. SynchronizedList(List<T> l)
  2462. {
  2463. super(l);
  2464. list = l;
  2465. }
  2466. /**
  2467. * Called only by trusted code to specify the mutex as well as the list.
  2468. * @param sync the mutex
  2469. * @param l the list
  2470. */
  2471. SynchronizedList(Object sync, List<T> l)
  2472. {
  2473. super(sync, l);
  2474. list = l;
  2475. }
  2476. /**
  2477. * Insert an element into the underlying list at a given position (optional
  2478. * operation). This shifts all existing elements from that position to the
  2479. * end one index to the right. This version of add has no return, since it is
  2480. * assumed to always succeed if there is no exception. Before the
  2481. * addition takes place, a lock is obtained on the mutex.
  2482. *
  2483. * @param index the location to insert the item
  2484. * @param o the object to insert
  2485. * @throws UnsupportedOperationException if this list does not support the
  2486. * add operation
  2487. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  2488. * @throws ClassCastException if o cannot be added to this list due to its
  2489. * type
  2490. * @throws IllegalArgumentException if o cannot be added to this list for
  2491. * some other reason
  2492. * @throws NullPointerException if o is null and this list doesn't support
  2493. * the addition of null values.
  2494. */
  2495. public void add(int index, T o)
  2496. {
  2497. synchronized (mutex)
  2498. {
  2499. list.add(index, o);
  2500. }
  2501. }
  2502. /**
  2503. * Add the contents of a collection to the underlying list at the given
  2504. * index (optional operation). If the list imposes restraints on what
  2505. * can be inserted, such as no null elements, this should be documented.
  2506. * A lock is obtained on the mutex before any of the elements are added.
  2507. *
  2508. * @param index the index at which to insert
  2509. * @param c the collection to add
  2510. * @return <code>true</code>, as defined by Collection for a modified list
  2511. * @throws UnsupportedOperationException if this list does not support the
  2512. * add operation
  2513. * @throws ClassCastException if o cannot be added to this list due to its
  2514. * type
  2515. * @throws IllegalArgumentException if o cannot be added to this list for
  2516. * some other reason
  2517. * @throws NullPointerException if o is null and this list doesn't support
  2518. * the addition of null values.
  2519. */
  2520. public boolean addAll(int index, Collection<? extends T> c)
  2521. {
  2522. synchronized (mutex)
  2523. {
  2524. return list.addAll(index, c);
  2525. }
  2526. }
  2527. /**
  2528. * Tests whether the underlying list is equal to the supplied object.
  2529. * The object is deemed to be equal if it is also a <code>List</code>
  2530. * of equal size and with the same elements (i.e. each element, e1,
  2531. * in list, l1, and each element, e2, in l2, must return <code>true</code> for
  2532. * <code>e1 == null ? e2 == null : e1.equals(e2)</code>. Before the
  2533. * comparison is made, a lock is obtained on the mutex.
  2534. *
  2535. * @param o The object to test for equality with the underlying list.
  2536. * @return <code>true</code> if o is equal to the underlying list under the above
  2537. * definition.
  2538. */
  2539. public boolean equals(Object o)
  2540. {
  2541. synchronized (mutex)
  2542. {
  2543. return list.equals(o);
  2544. }
  2545. }
  2546. /**
  2547. * Retrieves the object at the specified index. A lock
  2548. * is obtained on the mutex before the list is accessed.
  2549. *
  2550. * @param index the index of the element to be returned
  2551. * @return the element at index index in this list
  2552. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  2553. */
  2554. public T get(int index)
  2555. {
  2556. synchronized (mutex)
  2557. {
  2558. return list.get(index);
  2559. }
  2560. }
  2561. /**
  2562. * Obtains a hashcode for the underlying list, first obtaining
  2563. * a lock on the mutex. The calculation of the hashcode is
  2564. * detailed in the documentation for the <code>List</code>
  2565. * interface.
  2566. *
  2567. * @return The hashcode of the underlying list.
  2568. * @see List#hashCode()
  2569. */
  2570. public int hashCode()
  2571. {
  2572. synchronized (mutex)
  2573. {
  2574. return list.hashCode();
  2575. }
  2576. }
  2577. /**
  2578. * Obtain the first index at which a given object is to be found in the
  2579. * underlying list. A lock is obtained on the mutex before the list is
  2580. * accessed.
  2581. *
  2582. * @param o the object to search for
  2583. * @return the least integer n such that <code>o == null ? get(n) == null :
  2584. * o.equals(get(n))</code>, or -1 if there is no such index.
  2585. * @throws ClassCastException if the type of o is not a valid
  2586. * type for this list.
  2587. * @throws NullPointerException if o is null and this
  2588. * list does not support null values.
  2589. */
  2590. public int indexOf(Object o)
  2591. {
  2592. synchronized (mutex)
  2593. {
  2594. return list.indexOf(o);
  2595. }
  2596. }
  2597. /**
  2598. * Obtain the last index at which a given object is to be found in this
  2599. * underlying list. A lock is obtained on the mutex before the list
  2600. * is accessed.
  2601. *
  2602. * @return the greatest integer n such that <code>o == null ? get(n) == null
  2603. * : o.equals(get(n))</code>, or -1 if there is no such index.
  2604. * @throws ClassCastException if the type of o is not a valid
  2605. * type for this list.
  2606. * @throws NullPointerException if o is null and this
  2607. * list does not support null values.
  2608. */
  2609. public int lastIndexOf(Object o)
  2610. {
  2611. synchronized (mutex)
  2612. {
  2613. return list.lastIndexOf(o);
  2614. }
  2615. }
  2616. /**
  2617. * Retrieves a synchronized wrapper around the underlying list's
  2618. * list iterator. A lock is obtained on the mutex before the
  2619. * list iterator is retrieved.
  2620. *
  2621. * @return A list iterator over the elements in the underlying list.
  2622. * The list iterator allows additional list-specific operations
  2623. * to be performed, in addition to those supplied by the
  2624. * standard iterator.
  2625. */
  2626. public ListIterator<T> listIterator()
  2627. {
  2628. synchronized (mutex)
  2629. {
  2630. return new SynchronizedListIterator<T>(mutex, list.listIterator());
  2631. }
  2632. }
  2633. /**
  2634. * Retrieves a synchronized wrapper around the underlying list's
  2635. * list iterator. A lock is obtained on the mutex before the
  2636. * list iterator is retrieved. The iterator starts at the
  2637. * index supplied, leading to the element at that index being
  2638. * the first one returned by <code>next()</code>. Calling
  2639. * <code>previous()</code> from this initial position returns
  2640. * index - 1.
  2641. *
  2642. * @param index the position, between 0 and size() inclusive, to begin the
  2643. * iteration from
  2644. * @return A list iterator over the elements in the underlying list.
  2645. * The list iterator allows additional list-specific operations
  2646. * to be performed, in addition to those supplied by the
  2647. * standard iterator.
  2648. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  2649. */
  2650. public ListIterator<T> listIterator(int index)
  2651. {
  2652. synchronized (mutex)
  2653. {
  2654. return new SynchronizedListIterator<T>(mutex,
  2655. list.listIterator(index));
  2656. }
  2657. }
  2658. /**
  2659. * Remove the element at a given position in the underlying list (optional
  2660. * operation). All remaining elements are shifted to the left to fill the gap.
  2661. * A lock on the mutex is obtained before the element is removed.
  2662. *
  2663. * @param index the position within the list of the object to remove
  2664. * @return the object that was removed
  2665. * @throws UnsupportedOperationException if this list does not support the
  2666. * remove operation
  2667. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  2668. */
  2669. public T remove(int index)
  2670. {
  2671. synchronized (mutex)
  2672. {
  2673. return list.remove(index);
  2674. }
  2675. }
  2676. /**
  2677. * Replace an element of the underlying list with another object (optional
  2678. * operation). A lock is obtained on the mutex before the element is
  2679. * replaced.
  2680. *
  2681. * @param index the position within this list of the element to be replaced
  2682. * @param o the object to replace it with
  2683. * @return the object that was replaced
  2684. * @throws UnsupportedOperationException if this list does not support the
  2685. * set operation.
  2686. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  2687. * @throws ClassCastException if o cannot be added to this list due to its
  2688. * type
  2689. * @throws IllegalArgumentException if o cannot be added to this list for
  2690. * some other reason
  2691. * @throws NullPointerException if o is null and this
  2692. * list does not support null values.
  2693. */
  2694. public T set(int index, T o)
  2695. {
  2696. synchronized (mutex)
  2697. {
  2698. return list.set(index, o);
  2699. }
  2700. }
  2701. /**
  2702. * Obtain a List view of a subsection of the underlying list, from fromIndex
  2703. * (inclusive) to toIndex (exclusive). If the two indices are equal, the
  2704. * sublist is empty. The returned list should be modifiable if and only
  2705. * if this list is modifiable. Changes to the returned list should be
  2706. * reflected in this list. If this list is structurally modified in
  2707. * any way other than through the returned list, the result of any subsequent
  2708. * operations on the returned list is undefined. A lock is obtained
  2709. * on the mutex before the creation of the sublist. The returned list
  2710. * is also synchronized, using the same mutex.
  2711. *
  2712. * @param fromIndex the index that the returned list should start from
  2713. * (inclusive)
  2714. * @param toIndex the index that the returned list should go to (exclusive)
  2715. * @return a List backed by a subsection of this list
  2716. * @throws IndexOutOfBoundsException if fromIndex &lt; 0
  2717. * || toIndex &gt; size() || fromIndex &gt; toIndex
  2718. */
  2719. public List<T> subList(int fromIndex, int toIndex)
  2720. {
  2721. synchronized (mutex)
  2722. {
  2723. return new SynchronizedList<T>(mutex,
  2724. list.subList(fromIndex, toIndex));
  2725. }
  2726. }
  2727. } // class SynchronizedList
  2728. /**
  2729. * The implementation of {@link #synchronizedList(List)} for random-access
  2730. * lists. This class name is required for compatibility with Sun's JDK
  2731. * serializability.
  2732. *
  2733. * @author Eric Blake (ebb9@email.byu.edu)
  2734. */
  2735. private static final class SynchronizedRandomAccessList<T>
  2736. extends SynchronizedList<T> implements RandomAccess
  2737. {
  2738. /**
  2739. * Compatible with JDK 1.4.
  2740. */
  2741. private static final long serialVersionUID = 1530674583602358482L;
  2742. /**
  2743. * Wrap a given list.
  2744. * @param l the list to wrap
  2745. * @throws NullPointerException if l is null
  2746. */
  2747. SynchronizedRandomAccessList(List<T> l)
  2748. {
  2749. super(l);
  2750. }
  2751. /**
  2752. * Called only by trusted code to specify the mutex as well as the
  2753. * collection.
  2754. * @param sync the mutex
  2755. * @param l the list
  2756. */
  2757. SynchronizedRandomAccessList(Object sync, List<T> l)
  2758. {
  2759. super(sync, l);
  2760. }
  2761. /**
  2762. * Obtain a List view of a subsection of the underlying list, from fromIndex
  2763. * (inclusive) to toIndex (exclusive). If the two indices are equal, the
  2764. * sublist is empty. The returned list should be modifiable if and only
  2765. * if this list is modifiable. Changes to the returned list should be
  2766. * reflected in this list. If this list is structurally modified in
  2767. * any way other than through the returned list, the result of any subsequent
  2768. * operations on the returned list is undefined. A lock is obtained
  2769. * on the mutex before the creation of the sublist. The returned list
  2770. * is also synchronized, using the same mutex. Random accessibility
  2771. * is also extended to the new list.
  2772. *
  2773. * @param fromIndex the index that the returned list should start from
  2774. * (inclusive)
  2775. * @param toIndex the index that the returned list should go to (exclusive)
  2776. * @return a List backed by a subsection of this list
  2777. * @throws IndexOutOfBoundsException if fromIndex &lt; 0
  2778. * || toIndex &gt; size() || fromIndex &gt; toIndex
  2779. */
  2780. public List<T> subList(int fromIndex, int toIndex)
  2781. {
  2782. synchronized (mutex)
  2783. {
  2784. return new SynchronizedRandomAccessList<T>(mutex,
  2785. list.subList(fromIndex,
  2786. toIndex));
  2787. }
  2788. }
  2789. } // class SynchronizedRandomAccessList
  2790. /**
  2791. * The implementation of {@link SynchronizedList#listIterator()}. This
  2792. * iterator must "sync" on the same object as the list it iterates over.
  2793. *
  2794. * @author Eric Blake (ebb9@email.byu.edu)
  2795. */
  2796. private static final class SynchronizedListIterator<T>
  2797. extends SynchronizedIterator<T> implements ListIterator<T>
  2798. {
  2799. /**
  2800. * The wrapped iterator, stored both here and in the superclass to
  2801. * avoid excessive casting.
  2802. */
  2803. private final ListIterator<T> li;
  2804. /**
  2805. * Only trusted code creates a wrapper, with the specified sync.
  2806. * @param sync the mutex
  2807. * @param li the wrapped iterator
  2808. */
  2809. SynchronizedListIterator(Object sync, ListIterator<T> li)
  2810. {
  2811. super(sync, li);
  2812. this.li = li;
  2813. }
  2814. /**
  2815. * Insert an element into the underlying list at the current position of
  2816. * the iterator (optional operation). The element is inserted in between
  2817. * the element that would be returned by <code>previous()</code> and the
  2818. * element that would be returned by <code>next()</code>. After the
  2819. * insertion, a subsequent call to next is unaffected, but
  2820. * a call to previous returns the item that was added. The values returned
  2821. * by nextIndex() and previousIndex() are incremented. A lock is obtained
  2822. * on the mutex before the addition takes place.
  2823. *
  2824. * @param o the object to insert into the list
  2825. * @throws ClassCastException if the object is of a type which cannot be added
  2826. * to this list.
  2827. * @throws IllegalArgumentException if some other aspect of the object stops
  2828. * it being added to this list.
  2829. * @throws UnsupportedOperationException if this ListIterator does not
  2830. * support the add operation.
  2831. */
  2832. public void add(T o)
  2833. {
  2834. synchronized (mutex)
  2835. {
  2836. li.add(o);
  2837. }
  2838. }
  2839. /**
  2840. * Tests whether there are elements remaining in the underlying list
  2841. * in the reverse direction. In other words, <code>previous()</code>
  2842. * will not fail with a NoSuchElementException. A lock is obtained
  2843. * on the mutex before the check takes place.
  2844. *
  2845. * @return <code>true</code> if the list continues in the reverse direction
  2846. */
  2847. public boolean hasPrevious()
  2848. {
  2849. synchronized (mutex)
  2850. {
  2851. return li.hasPrevious();
  2852. }
  2853. }
  2854. /**
  2855. * Find the index of the element that would be returned by a call to
  2856. * <code>next()</code>. If hasNext() returns <code>false</code>, this
  2857. * returns the list size. A lock is obtained on the mutex before the
  2858. * query takes place.
  2859. *
  2860. * @return the index of the element that would be returned by next()
  2861. */
  2862. public int nextIndex()
  2863. {
  2864. synchronized (mutex)
  2865. {
  2866. return li.nextIndex();
  2867. }
  2868. }
  2869. /**
  2870. * Obtain the previous element from the underlying list. Repeated
  2871. * calls to previous may be used to iterate backwards over the entire list,
  2872. * or calls to next and previous may be used together to go forwards and
  2873. * backwards. Alternating calls to next and previous will return the same
  2874. * element. A lock is obtained on the mutex before the object is retrieved.
  2875. *
  2876. * @return the next element in the list in the reverse direction
  2877. * @throws NoSuchElementException if there are no more elements
  2878. */
  2879. public T previous()
  2880. {
  2881. synchronized (mutex)
  2882. {
  2883. return li.previous();
  2884. }
  2885. }
  2886. /**
  2887. * Find the index of the element that would be returned by a call to
  2888. * previous. If hasPrevious() returns <code>false</code>, this returns -1.
  2889. * A lock is obtained on the mutex before the query takes place.
  2890. *
  2891. * @return the index of the element that would be returned by previous()
  2892. */
  2893. public int previousIndex()
  2894. {
  2895. synchronized (mutex)
  2896. {
  2897. return li.previousIndex();
  2898. }
  2899. }
  2900. /**
  2901. * Replace the element last returned by a call to <code>next()</code> or
  2902. * <code>previous()</code> with a given object (optional operation). This
  2903. * method may only be called if neither <code>add()</code> nor
  2904. * <code>remove()</code> have been called since the last call to
  2905. * <code>next()</code> or <code>previous</code>. A lock is obtained
  2906. * on the mutex before the list is modified.
  2907. *
  2908. * @param o the object to replace the element with
  2909. * @throws ClassCastException the object is of a type which cannot be added
  2910. * to this list
  2911. * @throws IllegalArgumentException some other aspect of the object stops
  2912. * it being added to this list
  2913. * @throws IllegalStateException if neither next or previous have been
  2914. * called, or if add or remove has been called since the last call
  2915. * to next or previous
  2916. * @throws UnsupportedOperationException if this ListIterator does not
  2917. * support the set operation
  2918. */
  2919. public void set(T o)
  2920. {
  2921. synchronized (mutex)
  2922. {
  2923. li.set(o);
  2924. }
  2925. }
  2926. } // class SynchronizedListIterator
  2927. /**
  2928. * Returns a synchronized (thread-safe) map wrapper backed by the given
  2929. * map. Notice that element access through the collection views and their
  2930. * iterators are thread-safe, but if the map can be structurally modified
  2931. * (adding or removing elements) then you should synchronize around the
  2932. * iteration to avoid non-deterministic behavior:<br>
  2933. * <pre>
  2934. * Map m = Collections.synchronizedMap(new Map(...));
  2935. * ...
  2936. * Set s = m.keySet(); // safe outside a synchronized block
  2937. * synchronized (m) // synch on m, not s
  2938. * {
  2939. * Iterator i = s.iterator();
  2940. * while (i.hasNext())
  2941. * foo(i.next());
  2942. * }
  2943. * </pre><p>
  2944. *
  2945. * The returned Map implements Serializable, but can only be serialized if
  2946. * the map it wraps is likewise Serializable.
  2947. *
  2948. * @param m the map to wrap
  2949. * @return a synchronized view of the map
  2950. * @see Serializable
  2951. */
  2952. public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
  2953. {
  2954. return new SynchronizedMap<K, V>(m);
  2955. }
  2956. /**
  2957. * The implementation of {@link #synchronizedMap(Map)}. This
  2958. * class name is required for compatibility with Sun's JDK serializability.
  2959. *
  2960. * @author Eric Blake (ebb9@email.byu.edu)
  2961. */
  2962. private static class SynchronizedMap<K, V> implements Map<K, V>, Serializable
  2963. {
  2964. /**
  2965. * Compatible with JDK 1.4.
  2966. */
  2967. private static final long serialVersionUID = 1978198479659022715L;
  2968. /**
  2969. * The wrapped map.
  2970. * @serial the real map
  2971. */
  2972. private final Map<K, V> m;
  2973. /**
  2974. * The object to synchronize on. When an instance is created via public
  2975. * methods, it will be this; but other uses like
  2976. * SynchronizedSortedMap.subMap() must specify another mutex. Package
  2977. * visible for use by subclass.
  2978. * @serial the lock
  2979. */
  2980. final Object mutex;
  2981. /**
  2982. * Cache the entry set.
  2983. */
  2984. private transient Set<Map.Entry<K, V>> entries;
  2985. /**
  2986. * Cache the key set.
  2987. */
  2988. private transient Set<K> keys;
  2989. /**
  2990. * Cache the value collection.
  2991. */
  2992. private transient Collection<V> values;
  2993. /**
  2994. * Wrap a given map.
  2995. * @param m the map to wrap
  2996. * @throws NullPointerException if m is null
  2997. */
  2998. SynchronizedMap(Map<K, V> m)
  2999. {
  3000. this.m = m;
  3001. mutex = this;
  3002. if (m == null)
  3003. throw new NullPointerException();
  3004. }
  3005. /**
  3006. * Called only by trusted code to specify the mutex as well as the map.
  3007. * @param sync the mutex
  3008. * @param m the map
  3009. */
  3010. SynchronizedMap(Object sync, Map<K, V> m)
  3011. {
  3012. this.m = m;
  3013. mutex = sync;
  3014. }
  3015. /**
  3016. * Clears all the entries from the underlying map. A lock is obtained
  3017. * on the mutex before the map is cleared.
  3018. *
  3019. * @throws UnsupportedOperationException if clear is not supported
  3020. */
  3021. public void clear()
  3022. {
  3023. synchronized (mutex)
  3024. {
  3025. m.clear();
  3026. }
  3027. }
  3028. /**
  3029. * Returns <code>true</code> if the underlying map contains a entry for the given key.
  3030. * A lock is obtained on the mutex before the map is queried.
  3031. *
  3032. * @param key the key to search for.
  3033. * @return <code>true</code> if the underlying map contains the key.
  3034. * @throws ClassCastException if the key is of an inappropriate type.
  3035. * @throws NullPointerException if key is <code>null</code> but the map
  3036. * does not permit null keys.
  3037. */
  3038. public boolean containsKey(Object key)
  3039. {
  3040. synchronized (mutex)
  3041. {
  3042. return m.containsKey(key);
  3043. }
  3044. }
  3045. /**
  3046. * Returns <code>true</code> if the underlying map contains at least one entry with the
  3047. * given value. In other words, returns <code>true</code> if a value v exists where
  3048. * <code>(value == null ? v == null : value.equals(v))</code>. This usually
  3049. * requires linear time. A lock is obtained on the mutex before the map
  3050. * is queried.
  3051. *
  3052. * @param value the value to search for
  3053. * @return <code>true</code> if the map contains the value
  3054. * @throws ClassCastException if the type of the value is not a valid type
  3055. * for this map.
  3056. * @throws NullPointerException if the value is null and the map doesn't
  3057. * support null values.
  3058. */
  3059. public boolean containsValue(Object value)
  3060. {
  3061. synchronized (mutex)
  3062. {
  3063. return m.containsValue(value);
  3064. }
  3065. }
  3066. // This is one of the ickiest cases of nesting I've ever seen. It just
  3067. // means "return a SynchronizedSet, except that the iterator() method
  3068. // returns an SynchronizedIterator whose next() method returns a
  3069. // synchronized wrapper around its normal return value".
  3070. public Set<Map.Entry<K, V>> entrySet()
  3071. {
  3072. // Define this here to spare some nesting.
  3073. class SynchronizedMapEntry<K, V> implements Map.Entry<K, V>
  3074. {
  3075. final Map.Entry<K, V> e;
  3076. SynchronizedMapEntry(Map.Entry<K, V> o)
  3077. {
  3078. e = o;
  3079. }
  3080. /**
  3081. * Returns <code>true</code> if the object, o, implements <code>Map.Entry</code>
  3082. * with the same key and value as the underlying entry. A lock is
  3083. * obtained on the mutex before the comparison takes place.
  3084. *
  3085. * @param o The object to compare with this entry.
  3086. * @return <code>true</code> if o is equivalent to the underlying map entry.
  3087. */
  3088. public boolean equals(Object o)
  3089. {
  3090. synchronized (mutex)
  3091. {
  3092. return e.equals(o);
  3093. }
  3094. }
  3095. /**
  3096. * Returns the key used in the underlying map entry. A lock is obtained
  3097. * on the mutex before the key is retrieved.
  3098. *
  3099. * @return The key of the underlying map entry.
  3100. */
  3101. public K getKey()
  3102. {
  3103. synchronized (mutex)
  3104. {
  3105. return e.getKey();
  3106. }
  3107. }
  3108. /**
  3109. * Returns the value used in the underlying map entry. A lock is obtained
  3110. * on the mutex before the value is retrieved.
  3111. *
  3112. * @return The value of the underlying map entry.
  3113. */
  3114. public V getValue()
  3115. {
  3116. synchronized (mutex)
  3117. {
  3118. return e.getValue();
  3119. }
  3120. }
  3121. /**
  3122. * Computes the hash code for the underlying map entry.
  3123. * This computation is described in the documentation for the
  3124. * <code>Map</code> interface. A lock is obtained on the mutex
  3125. * before the underlying map is accessed.
  3126. *
  3127. * @return The hash code of the underlying map entry.
  3128. * @see Map#hashCode()
  3129. */
  3130. public int hashCode()
  3131. {
  3132. synchronized (mutex)
  3133. {
  3134. return e.hashCode();
  3135. }
  3136. }
  3137. /**
  3138. * Replaces the value in the underlying map entry with the specified
  3139. * object (optional operation). A lock is obtained on the mutex
  3140. * before the map is altered. The map entry, in turn, will alter
  3141. * the underlying map object. The operation is undefined if the
  3142. * <code>remove()</code> method of the iterator has been called
  3143. * beforehand.
  3144. *
  3145. * @param value the new value to store
  3146. * @return the old value
  3147. * @throws UnsupportedOperationException if the operation is not supported.
  3148. * @throws ClassCastException if the value is of the wrong type.
  3149. * @throws IllegalArgumentException if something about the value
  3150. * prevents it from existing in this map.
  3151. * @throws NullPointerException if the map forbids null values.
  3152. */
  3153. public V setValue(V value)
  3154. {
  3155. synchronized (mutex)
  3156. {
  3157. return e.setValue(value);
  3158. }
  3159. }
  3160. /**
  3161. * Returns a textual representation of the underlying map entry.
  3162. * A lock is obtained on the mutex before the entry is accessed.
  3163. *
  3164. * @return The contents of the map entry in <code>String</code> form.
  3165. */
  3166. public String toString()
  3167. {
  3168. synchronized (mutex)
  3169. {
  3170. return e.toString();
  3171. }
  3172. }
  3173. } // class SynchronizedMapEntry
  3174. // Now the actual code.
  3175. if (entries == null)
  3176. synchronized (mutex)
  3177. {
  3178. entries = new SynchronizedSet<Map.Entry<K, V>>(mutex, m.entrySet())
  3179. {
  3180. /**
  3181. * Returns an iterator over the set. The iterator has no specific order,
  3182. * unless further specified. A lock is obtained on the set's mutex
  3183. * before the iterator is created. The created iterator is also
  3184. * thread-safe.
  3185. *
  3186. * @return A synchronized set iterator.
  3187. */
  3188. public Iterator<Map.Entry<K, V>> iterator()
  3189. {
  3190. synchronized (super.mutex)
  3191. {
  3192. return new SynchronizedIterator<Map.Entry<K, V>>(super.mutex,
  3193. c.iterator())
  3194. {
  3195. /**
  3196. * Retrieves the next map entry from the iterator.
  3197. * A lock is obtained on the iterator's mutex before
  3198. * the entry is created. The new map entry is enclosed in
  3199. * a thread-safe wrapper.
  3200. *
  3201. * @return A synchronized map entry.
  3202. */
  3203. public Map.Entry<K, V> next()
  3204. {
  3205. synchronized (super.mutex)
  3206. {
  3207. return new SynchronizedMapEntry<K, V>(super.next());
  3208. }
  3209. }
  3210. };
  3211. }
  3212. }
  3213. };
  3214. }
  3215. return entries;
  3216. }
  3217. /**
  3218. * Returns <code>true</code> if the object, o, is also an instance
  3219. * of <code>Map</code> and contains an equivalent
  3220. * entry set to that of the underlying map. A lock
  3221. * is obtained on the mutex before the objects are
  3222. * compared.
  3223. *
  3224. * @param o The object to compare.
  3225. * @return <code>true</code> if o and the underlying map are equivalent.
  3226. */
  3227. public boolean equals(Object o)
  3228. {
  3229. synchronized (mutex)
  3230. {
  3231. return m.equals(o);
  3232. }
  3233. }
  3234. /**
  3235. * Returns the value associated with the given key, or null
  3236. * if no such mapping exists. An ambiguity exists with maps
  3237. * that accept null values as a return value of null could
  3238. * be due to a non-existent mapping or simply a null value
  3239. * for that key. To resolve this, <code>containsKey</code>
  3240. * should be used. A lock is obtained on the mutex before
  3241. * the value is retrieved from the underlying map.
  3242. *
  3243. * @param key The key of the required mapping.
  3244. * @return The value associated with the given key, or
  3245. * null if no such mapping exists.
  3246. * @throws ClassCastException if the key is an inappropriate type.
  3247. * @throws NullPointerException if this map does not accept null keys.
  3248. */
  3249. public V get(Object key)
  3250. {
  3251. synchronized (mutex)
  3252. {
  3253. return m.get(key);
  3254. }
  3255. }
  3256. /**
  3257. * Calculates the hash code of the underlying map as the
  3258. * sum of the hash codes of all entries. A lock is obtained
  3259. * on the mutex before the hash code is computed.
  3260. *
  3261. * @return The hash code of the underlying map.
  3262. */
  3263. public int hashCode()
  3264. {
  3265. synchronized (mutex)
  3266. {
  3267. return m.hashCode();
  3268. }
  3269. }
  3270. /**
  3271. * Returns <code>true</code> if the underlying map contains no entries.
  3272. * A lock is obtained on the mutex before the map is examined.
  3273. *
  3274. * @return <code>true</code> if the map is empty.
  3275. */
  3276. public boolean isEmpty()
  3277. {
  3278. synchronized (mutex)
  3279. {
  3280. return m.isEmpty();
  3281. }
  3282. }
  3283. /**
  3284. * Returns a thread-safe set view of the keys in the underlying map. The
  3285. * set is backed by the map, so that changes in one show up in the other.
  3286. * Modifications made while an iterator is in progress cause undefined
  3287. * behavior. If the set supports removal, these methods remove the
  3288. * underlying mapping from the map: <code>Iterator.remove</code>,
  3289. * <code>Set.remove</code>, <code>removeAll</code>, <code>retainAll</code>,
  3290. * and <code>clear</code>. Element addition, via <code>add</code> or
  3291. * <code>addAll</code>, is not supported via this set. A lock is obtained
  3292. * on the mutex before the set is created.
  3293. *
  3294. * @return A synchronized set containing the keys of the underlying map.
  3295. */
  3296. public Set<K> keySet()
  3297. {
  3298. if (keys == null)
  3299. synchronized (mutex)
  3300. {
  3301. keys = new SynchronizedSet<K>(mutex, m.keySet());
  3302. }
  3303. return keys;
  3304. }
  3305. /**
  3306. * Associates the given key to the given value (optional operation). If the
  3307. * underlying map already contains the key, its value is replaced. Be aware
  3308. * that in a map that permits <code>null</code> values, a null return does not
  3309. * always imply that the mapping was created. A lock is obtained on the mutex
  3310. * before the modification is made.
  3311. *
  3312. * @param key the key to map.
  3313. * @param value the value to be mapped.
  3314. * @return the previous value of the key, or null if there was no mapping
  3315. * @throws UnsupportedOperationException if the operation is not supported
  3316. * @throws ClassCastException if the key or value is of the wrong type
  3317. * @throws IllegalArgumentException if something about this key or value
  3318. * prevents it from existing in this map
  3319. * @throws NullPointerException if either the key or the value is null,
  3320. * and the map forbids null keys or values
  3321. * @see #containsKey(Object)
  3322. */
  3323. public V put(K key, V value)
  3324. {
  3325. synchronized (mutex)
  3326. {
  3327. return m.put(key, value);
  3328. }
  3329. }
  3330. /**
  3331. * Copies all entries of the given map to the underlying one (optional
  3332. * operation). If the map already contains a key, its value is replaced.
  3333. * A lock is obtained on the mutex before the operation proceeds.
  3334. *
  3335. * @param map the mapping to load into this map
  3336. * @throws UnsupportedOperationException if the operation is not supported
  3337. * @throws ClassCastException if a key or value is of the wrong type
  3338. * @throws IllegalArgumentException if something about a key or value
  3339. * prevents it from existing in this map
  3340. * @throws NullPointerException if the map forbids null keys or values, or
  3341. * if <code>m</code> is null.
  3342. * @see #put(Object, Object)
  3343. */
  3344. public void putAll(Map<? extends K, ? extends V> map)
  3345. {
  3346. synchronized (mutex)
  3347. {
  3348. m.putAll(map);
  3349. }
  3350. }
  3351. /**
  3352. * Removes the mapping for the key, o, if present (optional operation). If
  3353. * the key is not present, this returns null. Note that maps which permit
  3354. * null values may also return null if the key was removed. A prior
  3355. * <code>containsKey()</code> check is required to avoid this ambiguity.
  3356. * Before the mapping is removed, a lock is obtained on the mutex.
  3357. *
  3358. * @param o the key to remove
  3359. * @return the value the key mapped to, or null if not present
  3360. * @throws UnsupportedOperationException if deletion is unsupported
  3361. * @throws NullPointerException if the key is null and this map doesn't
  3362. * support null keys.
  3363. * @throws ClassCastException if the type of the key is not a valid type
  3364. * for this map.
  3365. */
  3366. public V remove(Object o)
  3367. {
  3368. synchronized (mutex)
  3369. {
  3370. return m.remove(o);
  3371. }
  3372. }
  3373. /**
  3374. * Retrieves the size of the underlying map. A lock
  3375. * is obtained on the mutex before access takes place.
  3376. * Maps with a size greater than <code>Integer.MAX_VALUE</code>
  3377. * return <code>Integer.MAX_VALUE</code> instead.
  3378. *
  3379. * @return The size of the underlying map.
  3380. */
  3381. public int size()
  3382. {
  3383. synchronized (mutex)
  3384. {
  3385. return m.size();
  3386. }
  3387. }
  3388. /**
  3389. * Returns a textual representation of the underlying
  3390. * map. A lock is obtained on the mutex before the map
  3391. * is accessed.
  3392. *
  3393. * @return The map in <code>String</code> form.
  3394. */
  3395. public String toString()
  3396. {
  3397. synchronized (mutex)
  3398. {
  3399. return m.toString();
  3400. }
  3401. }
  3402. /**
  3403. * Returns a synchronized collection view of the values in the underlying
  3404. * map. The collection is backed by the map, so that changes in one show up in
  3405. * the other. Modifications made while an iterator is in progress cause
  3406. * undefined behavior. If the collection supports removal, these methods
  3407. * remove the underlying mapping from the map: <code>Iterator.remove</code>,
  3408. * <code>Collection.remove</code>, <code>removeAll</code>,
  3409. * <code>retainAll</code>, and <code>clear</code>. Element addition, via
  3410. * <code>add</code> or <code>addAll</code>, is not supported via this
  3411. * collection. A lock is obtained on the mutex before the collection
  3412. * is created.
  3413. *
  3414. * @return the collection of all values in the underlying map.
  3415. */
  3416. public Collection<V> values()
  3417. {
  3418. if (values == null)
  3419. synchronized (mutex)
  3420. {
  3421. values = new SynchronizedCollection<V>(mutex, m.values());
  3422. }
  3423. return values;
  3424. }
  3425. } // class SynchronizedMap
  3426. /**
  3427. * Returns a synchronized (thread-safe) set wrapper backed by the given
  3428. * set. Notice that element access through the iterator is thread-safe, but
  3429. * if the set can be structurally modified (adding or removing elements)
  3430. * then you should synchronize around the iteration to avoid
  3431. * non-deterministic behavior:<br>
  3432. * <pre>
  3433. * Set s = Collections.synchronizedSet(new Set(...));
  3434. * ...
  3435. * synchronized (s)
  3436. * {
  3437. * Iterator i = s.iterator();
  3438. * while (i.hasNext())
  3439. * foo(i.next());
  3440. * }
  3441. * </pre><p>
  3442. *
  3443. * The returned Set implements Serializable, but can only be serialized if
  3444. * the set it wraps is likewise Serializable.
  3445. *
  3446. * @param s the set to wrap
  3447. * @return a synchronized view of the set
  3448. * @see Serializable
  3449. */
  3450. public static <T> Set<T> synchronizedSet(Set<T> s)
  3451. {
  3452. return new SynchronizedSet<T>(s);
  3453. }
  3454. /**
  3455. * The implementation of {@link #synchronizedSet(Set)}. This class
  3456. * name is required for compatibility with Sun's JDK serializability.
  3457. * Package visible, so that sets such as Hashtable.keySet()
  3458. * can specify which object to synchronize on.
  3459. *
  3460. * @author Eric Blake (ebb9@email.byu.edu)
  3461. */
  3462. static class SynchronizedSet<T> extends SynchronizedCollection<T>
  3463. implements Set<T>
  3464. {
  3465. /**
  3466. * Compatible with JDK 1.4.
  3467. */
  3468. private static final long serialVersionUID = 487447009682186044L;
  3469. /**
  3470. * Wrap a given set.
  3471. * @param s the set to wrap
  3472. * @throws NullPointerException if s is null
  3473. */
  3474. SynchronizedSet(Set<T> s)
  3475. {
  3476. super(s);
  3477. }
  3478. /**
  3479. * Called only by trusted code to specify the mutex as well as the set.
  3480. * @param sync the mutex
  3481. * @param s the set
  3482. */
  3483. SynchronizedSet(Object sync, Set<T> s)
  3484. {
  3485. super(sync, s);
  3486. }
  3487. /**
  3488. * Returns <code>true</code> if the object, o, is a <code>Set</code>
  3489. * of the same size as the underlying set, and contains
  3490. * each element, e, which occurs in the underlying set.
  3491. * A lock is obtained on the mutex before the comparison
  3492. * takes place.
  3493. *
  3494. * @param o The object to compare against.
  3495. * @return <code>true</code> if o is an equivalent set.
  3496. */
  3497. public boolean equals(Object o)
  3498. {
  3499. synchronized (mutex)
  3500. {
  3501. return c.equals(o);
  3502. }
  3503. }
  3504. /**
  3505. * Computes the hash code for the underlying set as the
  3506. * sum of the hash code of all elements within the set.
  3507. * A lock is obtained on the mutex before the computation
  3508. * occurs.
  3509. *
  3510. * @return The hash code for the underlying set.
  3511. */
  3512. public int hashCode()
  3513. {
  3514. synchronized (mutex)
  3515. {
  3516. return c.hashCode();
  3517. }
  3518. }
  3519. } // class SynchronizedSet
  3520. /**
  3521. * Returns a synchronized (thread-safe) sorted map wrapper backed by the
  3522. * given map. Notice that element access through the collection views,
  3523. * subviews, and their iterators are thread-safe, but if the map can be
  3524. * structurally modified (adding or removing elements) then you should
  3525. * synchronize around the iteration to avoid non-deterministic behavior:<br>
  3526. * <pre>
  3527. * SortedMap m = Collections.synchronizedSortedMap(new SortedMap(...));
  3528. * ...
  3529. * Set s = m.keySet(); // safe outside a synchronized block
  3530. * SortedMap m2 = m.headMap(foo); // safe outside a synchronized block
  3531. * Set s2 = m2.keySet(); // safe outside a synchronized block
  3532. * synchronized (m) // synch on m, not m2, s or s2
  3533. * {
  3534. * Iterator i = s.iterator();
  3535. * while (i.hasNext())
  3536. * foo(i.next());
  3537. * i = s2.iterator();
  3538. * while (i.hasNext())
  3539. * bar(i.next());
  3540. * }
  3541. * </pre><p>
  3542. *
  3543. * The returned SortedMap implements Serializable, but can only be
  3544. * serialized if the map it wraps is likewise Serializable.
  3545. *
  3546. * @param m the sorted map to wrap
  3547. * @return a synchronized view of the sorted map
  3548. * @see Serializable
  3549. */
  3550. public static <K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> m)
  3551. {
  3552. return new SynchronizedSortedMap<K, V>(m);
  3553. }
  3554. /**
  3555. * The implementation of {@link #synchronizedSortedMap(SortedMap)}. This
  3556. * class name is required for compatibility with Sun's JDK serializability.
  3557. *
  3558. * @author Eric Blake (ebb9@email.byu.edu)
  3559. */
  3560. private static final class SynchronizedSortedMap<K, V>
  3561. extends SynchronizedMap<K, V>
  3562. implements SortedMap<K, V>
  3563. {
  3564. /**
  3565. * Compatible with JDK 1.4.
  3566. */
  3567. private static final long serialVersionUID = -8798146769416483793L;
  3568. /**
  3569. * The wrapped map; stored both here and in the superclass to avoid
  3570. * excessive casting.
  3571. * @serial the wrapped map
  3572. */
  3573. private final SortedMap<K, V> sm;
  3574. /**
  3575. * Wrap a given map.
  3576. * @param sm the map to wrap
  3577. * @throws NullPointerException if sm is null
  3578. */
  3579. SynchronizedSortedMap(SortedMap<K, V> sm)
  3580. {
  3581. super(sm);
  3582. this.sm = sm;
  3583. }
  3584. /**
  3585. * Called only by trusted code to specify the mutex as well as the map.
  3586. * @param sync the mutex
  3587. * @param sm the map
  3588. */
  3589. SynchronizedSortedMap(Object sync, SortedMap<K, V> sm)
  3590. {
  3591. super(sync, sm);
  3592. this.sm = sm;
  3593. }
  3594. /**
  3595. * Returns the comparator used in sorting the underlying map, or null if
  3596. * it is the keys' natural ordering. A lock is obtained on the mutex
  3597. * before the comparator is retrieved.
  3598. *
  3599. * @return the sorting comparator.
  3600. */
  3601. public Comparator<? super K> comparator()
  3602. {
  3603. synchronized (mutex)
  3604. {
  3605. return sm.comparator();
  3606. }
  3607. }
  3608. /**
  3609. * Returns the first, lowest sorted, key from the underlying map.
  3610. * A lock is obtained on the mutex before the map is accessed.
  3611. *
  3612. * @return the first key.
  3613. * @throws NoSuchElementException if this map is empty.
  3614. */
  3615. public K firstKey()
  3616. {
  3617. synchronized (mutex)
  3618. {
  3619. return sm.firstKey();
  3620. }
  3621. }
  3622. /**
  3623. * Returns a submap containing the keys from the first
  3624. * key (as returned by <code>firstKey()</code>) to
  3625. * the key before that specified. The submap supports all
  3626. * operations supported by the underlying map and all actions
  3627. * taking place on the submap are also reflected in the underlying
  3628. * map. A lock is obtained on the mutex prior to submap creation.
  3629. * This operation is equivalent to <code>subMap(firstKey(), toKey)</code>.
  3630. * The submap retains the thread-safe status of this map.
  3631. *
  3632. * @param toKey the exclusive upper range of the submap.
  3633. * @return a submap from <code>firstKey()</code> to the
  3634. * the key preceding toKey.
  3635. * @throws ClassCastException if toKey is not comparable to the underlying
  3636. * map's contents.
  3637. * @throws IllegalArgumentException if toKey is outside the map's range.
  3638. * @throws NullPointerException if toKey is null. but the map does not allow
  3639. * null keys.
  3640. */
  3641. public SortedMap<K, V> headMap(K toKey)
  3642. {
  3643. synchronized (mutex)
  3644. {
  3645. return new SynchronizedSortedMap<K, V>(mutex, sm.headMap(toKey));
  3646. }
  3647. }
  3648. /**
  3649. * Returns the last, highest sorted, key from the underlying map.
  3650. * A lock is obtained on the mutex before the map is accessed.
  3651. *
  3652. * @return the last key.
  3653. * @throws NoSuchElementException if this map is empty.
  3654. */
  3655. public K lastKey()
  3656. {
  3657. synchronized (mutex)
  3658. {
  3659. return sm.lastKey();
  3660. }
  3661. }
  3662. /**
  3663. * Returns a submap containing the keys from fromKey to
  3664. * the key before toKey. The submap supports all
  3665. * operations supported by the underlying map and all actions
  3666. * taking place on the submap are also reflected in the underlying
  3667. * map. A lock is obtained on the mutex prior to submap creation.
  3668. * The submap retains the thread-safe status of this map.
  3669. *
  3670. * @param fromKey the inclusive lower range of the submap.
  3671. * @param toKey the exclusive upper range of the submap.
  3672. * @return a submap from fromKey to the key preceding toKey.
  3673. * @throws ClassCastException if fromKey or toKey is not comparable
  3674. * to the underlying map's contents.
  3675. * @throws IllegalArgumentException if fromKey or toKey is outside the map's
  3676. * range.
  3677. * @throws NullPointerException if fromKey or toKey is null. but the map does
  3678. * not allow null keys.
  3679. */
  3680. public SortedMap<K, V> subMap(K fromKey, K toKey)
  3681. {
  3682. synchronized (mutex)
  3683. {
  3684. return new SynchronizedSortedMap<K, V>(mutex,
  3685. sm.subMap(fromKey, toKey));
  3686. }
  3687. }
  3688. /**
  3689. * Returns a submap containing all the keys from fromKey onwards.
  3690. * The submap supports all operations supported by the underlying
  3691. * map and all actions taking place on the submap are also reflected
  3692. * in the underlying map. A lock is obtained on the mutex prior to
  3693. * submap creation. The submap retains the thread-safe status of
  3694. * this map.
  3695. *
  3696. * @param fromKey the inclusive lower range of the submap.
  3697. * @return a submap from fromKey to <code>lastKey()</code>.
  3698. * @throws ClassCastException if fromKey is not comparable to the underlying
  3699. * map's contents.
  3700. * @throws IllegalArgumentException if fromKey is outside the map's range.
  3701. * @throws NullPointerException if fromKey is null. but the map does not allow
  3702. * null keys.
  3703. */
  3704. public SortedMap<K, V> tailMap(K fromKey)
  3705. {
  3706. synchronized (mutex)
  3707. {
  3708. return new SynchronizedSortedMap<K, V>(mutex, sm.tailMap(fromKey));
  3709. }
  3710. }
  3711. } // class SynchronizedSortedMap
  3712. /**
  3713. * Returns a synchronized (thread-safe) sorted set wrapper backed by the
  3714. * given set. Notice that element access through the iterator and through
  3715. * subviews are thread-safe, but if the set can be structurally modified
  3716. * (adding or removing elements) then you should synchronize around the
  3717. * iteration to avoid non-deterministic behavior:<br>
  3718. * <pre>
  3719. * SortedSet s = Collections.synchronizedSortedSet(new SortedSet(...));
  3720. * ...
  3721. * SortedSet s2 = s.headSet(foo); // safe outside a synchronized block
  3722. * synchronized (s) // synch on s, not s2
  3723. * {
  3724. * Iterator i = s2.iterator();
  3725. * while (i.hasNext())
  3726. * foo(i.next());
  3727. * }
  3728. * </pre><p>
  3729. *
  3730. * The returned SortedSet implements Serializable, but can only be
  3731. * serialized if the set it wraps is likewise Serializable.
  3732. *
  3733. * @param s the sorted set to wrap
  3734. * @return a synchronized view of the sorted set
  3735. * @see Serializable
  3736. */
  3737. public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
  3738. {
  3739. return new SynchronizedSortedSet<T>(s);
  3740. }
  3741. /**
  3742. * The implementation of {@link #synchronizedSortedSet(SortedSet)}. This
  3743. * class name is required for compatibility with Sun's JDK serializability.
  3744. *
  3745. * @author Eric Blake (ebb9@email.byu.edu)
  3746. */
  3747. private static final class SynchronizedSortedSet<T>
  3748. extends SynchronizedSet<T>
  3749. implements SortedSet<T>
  3750. {
  3751. /**
  3752. * Compatible with JDK 1.4.
  3753. */
  3754. private static final long serialVersionUID = 8695801310862127406L;
  3755. /**
  3756. * The wrapped set; stored both here and in the superclass to avoid
  3757. * excessive casting.
  3758. * @serial the wrapped set
  3759. */
  3760. private final SortedSet<T> ss;
  3761. /**
  3762. * Wrap a given set.
  3763. * @param ss the set to wrap
  3764. * @throws NullPointerException if ss is null
  3765. */
  3766. SynchronizedSortedSet(SortedSet<T> ss)
  3767. {
  3768. super(ss);
  3769. this.ss = ss;
  3770. }
  3771. /**
  3772. * Called only by trusted code to specify the mutex as well as the set.
  3773. * @param sync the mutex
  3774. * @param ss the set
  3775. */
  3776. SynchronizedSortedSet(Object sync, SortedSet<T> ss)
  3777. {
  3778. super(sync, ss);
  3779. this.ss = ss;
  3780. }
  3781. /**
  3782. * Returns the comparator used in sorting the underlying set, or null if
  3783. * it is the elements' natural ordering. A lock is obtained on the mutex
  3784. * before the comparator is retrieved.
  3785. *
  3786. * @return the sorting comparator.
  3787. */
  3788. public Comparator<? super T> comparator()
  3789. {
  3790. synchronized (mutex)
  3791. {
  3792. return ss.comparator();
  3793. }
  3794. }
  3795. /**
  3796. * Returns the first, lowest sorted, element from the underlying set.
  3797. * A lock is obtained on the mutex before the set is accessed.
  3798. *
  3799. * @return the first element.
  3800. * @throws NoSuchElementException if this set is empty.
  3801. */
  3802. public T first()
  3803. {
  3804. synchronized (mutex)
  3805. {
  3806. return ss.first();
  3807. }
  3808. }
  3809. /**
  3810. * Returns a subset containing the element from the first
  3811. * element (as returned by <code>first()</code>) to
  3812. * the element before that specified. The subset supports all
  3813. * operations supported by the underlying set and all actions
  3814. * taking place on the subset are also reflected in the underlying
  3815. * set. A lock is obtained on the mutex prior to subset creation.
  3816. * This operation is equivalent to <code>subSet(first(), toElement)</code>.
  3817. * The subset retains the thread-safe status of this set.
  3818. *
  3819. * @param toElement the exclusive upper range of the subset.
  3820. * @return a subset from <code>first()</code> to the
  3821. * the element preceding toElement.
  3822. * @throws ClassCastException if toElement is not comparable to the underlying
  3823. * set's contents.
  3824. * @throws IllegalArgumentException if toElement is outside the set's range.
  3825. * @throws NullPointerException if toElement is null. but the set does not allow
  3826. * null elements.
  3827. */
  3828. public SortedSet<T> headSet(T toElement)
  3829. {
  3830. synchronized (mutex)
  3831. {
  3832. return new SynchronizedSortedSet<T>(mutex, ss.headSet(toElement));
  3833. }
  3834. }
  3835. /**
  3836. * Returns the last, highest sorted, element from the underlying set.
  3837. * A lock is obtained on the mutex before the set is accessed.
  3838. *
  3839. * @return the last element.
  3840. * @throws NoSuchElementException if this set is empty.
  3841. */
  3842. public T last()
  3843. {
  3844. synchronized (mutex)
  3845. {
  3846. return ss.last();
  3847. }
  3848. }
  3849. /**
  3850. * Returns a subset containing the elements from fromElement to
  3851. * the element before toElement. The subset supports all
  3852. * operations supported by the underlying set and all actions
  3853. * taking place on the subset are also reflected in the underlying
  3854. * set. A lock is obtained on the mutex prior to subset creation.
  3855. * The subset retains the thread-safe status of this set.
  3856. *
  3857. * @param fromElement the inclusive lower range of the subset.
  3858. * @param toElement the exclusive upper range of the subset.
  3859. * @return a subset from fromElement to the element preceding toElement.
  3860. * @throws ClassCastException if fromElement or toElement is not comparable
  3861. * to the underlying set's contents.
  3862. * @throws IllegalArgumentException if fromElement or toElement is outside the set's
  3863. * range.
  3864. * @throws NullPointerException if fromElement or toElement is null. but the set does
  3865. * not allow null elements.
  3866. */
  3867. public SortedSet<T> subSet(T fromElement, T toElement)
  3868. {
  3869. synchronized (mutex)
  3870. {
  3871. return new SynchronizedSortedSet<T>(mutex,
  3872. ss.subSet(fromElement,
  3873. toElement));
  3874. }
  3875. }
  3876. /**
  3877. * Returns a subset containing all the elements from fromElement onwards.
  3878. * The subset supports all operations supported by the underlying
  3879. * set and all actions taking place on the subset are also reflected
  3880. * in the underlying set. A lock is obtained on the mutex prior to
  3881. * subset creation. The subset retains the thread-safe status of
  3882. * this set.
  3883. *
  3884. * @param fromElement the inclusive lower range of the subset.
  3885. * @return a subset from fromElement to <code>last()</code>.
  3886. * @throws ClassCastException if fromElement is not comparable to the underlying
  3887. * set's contents.
  3888. * @throws IllegalArgumentException if fromElement is outside the set's range.
  3889. * @throws NullPointerException if fromElement is null. but the set does not allow
  3890. * null elements.
  3891. */
  3892. public SortedSet<T> tailSet(T fromElement)
  3893. {
  3894. synchronized (mutex)
  3895. {
  3896. return new SynchronizedSortedSet<T>(mutex, ss.tailSet(fromElement));
  3897. }
  3898. }
  3899. } // class SynchronizedSortedSet
  3900. /**
  3901. * Returns an unmodifiable view of the given collection. This allows
  3902. * "read-only" access, although changes in the backing collection show up
  3903. * in this view. Attempts to modify the collection directly or via iterators
  3904. * will fail with {@link UnsupportedOperationException}. Although this view
  3905. * prevents changes to the structure of the collection and its elements, the values
  3906. * referenced by the objects in the collection can still be modified.
  3907. * <p>
  3908. *
  3909. * Since the collection might be a List or a Set, and those have incompatible
  3910. * equals and hashCode requirements, this relies on Object's implementation
  3911. * rather than passing those calls on to the wrapped collection. The returned
  3912. * Collection implements Serializable, but can only be serialized if
  3913. * the collection it wraps is likewise Serializable.
  3914. *
  3915. * @param c the collection to wrap
  3916. * @return a read-only view of the collection
  3917. * @see Serializable
  3918. */
  3919. public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
  3920. {
  3921. return new UnmodifiableCollection<T>(c);
  3922. }
  3923. /**
  3924. * The implementation of {@link #unmodifiableCollection(Collection)}. This
  3925. * class name is required for compatibility with Sun's JDK serializability.
  3926. *
  3927. * @author Eric Blake (ebb9@email.byu.edu)
  3928. */
  3929. private static class UnmodifiableCollection<T>
  3930. implements Collection<T>, Serializable
  3931. {
  3932. /**
  3933. * Compatible with JDK 1.4.
  3934. */
  3935. private static final long serialVersionUID = 1820017752578914078L;
  3936. /**
  3937. * The wrapped collection. Package visible for use by subclasses.
  3938. * @serial the real collection
  3939. */
  3940. final Collection<? extends T> c;
  3941. /**
  3942. * Wrap a given collection.
  3943. * @param c the collection to wrap
  3944. * @throws NullPointerException if c is null
  3945. */
  3946. UnmodifiableCollection(Collection<? extends T> c)
  3947. {
  3948. this.c = c;
  3949. if (c == null)
  3950. throw new NullPointerException();
  3951. }
  3952. /**
  3953. * Blocks the addition of elements to the underlying collection.
  3954. * This method never returns, throwing an exception instead.
  3955. *
  3956. * @param o the object to add.
  3957. * @return <code>true</code> if the collection was modified as a result of this action.
  3958. * @throws UnsupportedOperationException as an unmodifiable collection does not
  3959. * support the add operation.
  3960. */
  3961. public boolean add(T o)
  3962. {
  3963. throw new UnsupportedOperationException();
  3964. }
  3965. /**
  3966. * Blocks the addition of a collection of elements to the underlying
  3967. * collection. This method never returns, throwing an exception instead.
  3968. *
  3969. * @param c the collection to add.
  3970. * @return <code>true</code> if the collection was modified as a result of this action.
  3971. * @throws UnsupportedOperationException as an unmodifiable collection does not
  3972. * support the <code>addAll</code> operation.
  3973. */
  3974. public boolean addAll(Collection<? extends T> c)
  3975. {
  3976. throw new UnsupportedOperationException();
  3977. }
  3978. /**
  3979. * Blocks the clearing of the underlying collection. This method never
  3980. * returns, throwing an exception instead.
  3981. *
  3982. * @throws UnsupportedOperationException as an unmodifiable collection does
  3983. * not support the <code>clear()</code> operation.
  3984. */
  3985. public void clear()
  3986. {
  3987. throw new UnsupportedOperationException();
  3988. }
  3989. /**
  3990. * Test whether the underlying collection contains a given object as one of its
  3991. * elements.
  3992. *
  3993. * @param o the element to look for.
  3994. * @return <code>true</code> if the underlying collection contains at least
  3995. * one element e such that
  3996. * <code>o == null ? e == null : o.equals(e)</code>.
  3997. * @throws ClassCastException if the type of o is not a valid type for the
  3998. * underlying collection.
  3999. * @throws NullPointerException if o is null and the underlying collection
  4000. * doesn't support null values.
  4001. */
  4002. public boolean contains(Object o)
  4003. {
  4004. return c.contains(o);
  4005. }
  4006. /**
  4007. * Test whether the underlying collection contains every element in a given
  4008. * collection.
  4009. *
  4010. * @param c1 the collection to test for.
  4011. * @return <code>true</code> if for every element o in c, contains(o) would
  4012. * return <code>true</code>.
  4013. * @throws ClassCastException if the type of any element in c is not a valid
  4014. * type for the underlying collection.
  4015. * @throws NullPointerException if some element of c is null and the underlying
  4016. * collection does not support null values.
  4017. * @throws NullPointerException if c itself is null.
  4018. */
  4019. public boolean containsAll(Collection<?> c1)
  4020. {
  4021. return c.containsAll(c1);
  4022. }
  4023. /**
  4024. * Tests whether the underlying collection is empty, that is,
  4025. * if size() == 0.
  4026. *
  4027. * @return <code>true</code> if this collection contains no elements.
  4028. */
  4029. public boolean isEmpty()
  4030. {
  4031. return c.isEmpty();
  4032. }
  4033. /**
  4034. * Obtain an Iterator over the underlying collection, which maintains
  4035. * its unmodifiable nature.
  4036. *
  4037. * @return an UnmodifiableIterator over the elements of the underlying
  4038. * collection, in any order.
  4039. */
  4040. public Iterator<T> iterator()
  4041. {
  4042. return new UnmodifiableIterator<T>(c.iterator());
  4043. }
  4044. /**
  4045. * Blocks the removal of an object from the underlying collection.
  4046. * This method never returns, throwing an exception instead.
  4047. *
  4048. * @param o The object to remove.
  4049. * @return <code>true</code> if the object was removed (i.e. the underlying
  4050. * collection returned 1 or more instances of o).
  4051. * @throws UnsupportedOperationException as an unmodifiable collection
  4052. * does not support the <code>remove()</code> operation.
  4053. */
  4054. public boolean remove(Object o)
  4055. {
  4056. throw new UnsupportedOperationException();
  4057. }
  4058. /**
  4059. * Blocks the removal of a collection of objects from the underlying
  4060. * collection. This method never returns, throwing an exception
  4061. * instead.
  4062. *
  4063. * @param c The collection of objects to remove.
  4064. * @return <code>true</code> if the collection was modified.
  4065. * @throws UnsupportedOperationException as an unmodifiable collection
  4066. * does not support the <code>removeAll()</code> operation.
  4067. */
  4068. public boolean removeAll(Collection<?> c)
  4069. {
  4070. throw new UnsupportedOperationException();
  4071. }
  4072. /**
  4073. * Blocks the removal of all elements from the underlying collection,
  4074. * except those in the supplied collection. This method never returns,
  4075. * throwing an exception instead.
  4076. *
  4077. * @param c The collection of objects to retain.
  4078. * @return <code>true</code> if the collection was modified.
  4079. * @throws UnsupportedOperationException as an unmodifiable collection
  4080. * does not support the <code>retainAll()</code> operation.
  4081. */
  4082. public boolean retainAll(Collection<?> c)
  4083. {
  4084. throw new UnsupportedOperationException();
  4085. }
  4086. /**
  4087. * Retrieves the number of elements in the underlying collection.
  4088. *
  4089. * @return the number of elements in the collection.
  4090. */
  4091. public int size()
  4092. {
  4093. return c.size();
  4094. }
  4095. /**
  4096. * Copy the current contents of the underlying collection into an array.
  4097. *
  4098. * @return an array of type Object[] with a length equal to the size of the
  4099. * underlying collection and containing the elements currently in
  4100. * the underlying collection, in any order.
  4101. */
  4102. public Object[] toArray()
  4103. {
  4104. return c.toArray();
  4105. }
  4106. /**
  4107. * Copy the current contents of the underlying collection into an array. If
  4108. * the array passed as an argument has length less than the size of the
  4109. * underlying collection, an array of the same run-time type as a, with a length
  4110. * equal to the size of the underlying collection, is allocated using reflection.
  4111. * Otherwise, a itself is used. The elements of the underlying collection are
  4112. * copied into it, and if there is space in the array, the following element is
  4113. * set to null. The resultant array is returned.
  4114. * Note: The fact that the following element is set to null is only useful
  4115. * if it is known that this collection does not contain any null elements.
  4116. *
  4117. * @param a the array to copy this collection into.
  4118. * @return an array containing the elements currently in the underlying
  4119. * collection, in any order.
  4120. * @throws ArrayStoreException if the type of any element of the
  4121. * collection is not a subtype of the element type of a.
  4122. */
  4123. public <S> S[] toArray(S[] a)
  4124. {
  4125. return c.toArray(a);
  4126. }
  4127. /**
  4128. * A textual representation of the unmodifiable collection.
  4129. *
  4130. * @return The unmodifiable collection in the form of a <code>String</code>.
  4131. */
  4132. public String toString()
  4133. {
  4134. return c.toString();
  4135. }
  4136. } // class UnmodifiableCollection
  4137. /**
  4138. * The implementation of the various iterator methods in the
  4139. * unmodifiable classes.
  4140. *
  4141. * @author Eric Blake (ebb9@email.byu.edu)
  4142. */
  4143. private static class UnmodifiableIterator<T> implements Iterator<T>
  4144. {
  4145. /**
  4146. * The wrapped iterator.
  4147. */
  4148. private final Iterator<? extends T> i;
  4149. /**
  4150. * Only trusted code creates a wrapper.
  4151. * @param i the wrapped iterator
  4152. */
  4153. UnmodifiableIterator(Iterator<? extends T> i)
  4154. {
  4155. this.i = i;
  4156. }
  4157. /**
  4158. * Obtains the next element in the underlying collection.
  4159. *
  4160. * @return the next element in the collection.
  4161. * @throws NoSuchElementException if there are no more elements.
  4162. */
  4163. public T next()
  4164. {
  4165. return i.next();
  4166. }
  4167. /**
  4168. * Tests whether there are still elements to be retrieved from the
  4169. * underlying collection by <code>next()</code>. When this method
  4170. * returns <code>true</code>, an exception will not be thrown on calling
  4171. * <code>next()</code>.
  4172. *
  4173. * @return <code>true</code> if there is at least one more element in the underlying
  4174. * collection.
  4175. */
  4176. public boolean hasNext()
  4177. {
  4178. return i.hasNext();
  4179. }
  4180. /**
  4181. * Blocks the removal of elements from the underlying collection by the
  4182. * iterator.
  4183. *
  4184. * @throws UnsupportedOperationException as an unmodifiable collection
  4185. * does not support the removal of elements by its iterator.
  4186. */
  4187. public void remove()
  4188. {
  4189. throw new UnsupportedOperationException();
  4190. }
  4191. } // class UnmodifiableIterator
  4192. /**
  4193. * Returns an unmodifiable view of the given list. This allows
  4194. * "read-only" access, although changes in the backing list show up
  4195. * in this view. Attempts to modify the list directly, via iterators, or
  4196. * via sublists, will fail with {@link UnsupportedOperationException}.
  4197. * Although this view prevents changes to the structure of the list and
  4198. * its elements, the values referenced by the objects in the list can
  4199. * still be modified.
  4200. * <p>
  4201. *
  4202. * The returned List implements Serializable, but can only be serialized if
  4203. * the list it wraps is likewise Serializable. In addition, if the wrapped
  4204. * list implements RandomAccess, this does too.
  4205. *
  4206. * @param l the list to wrap
  4207. * @return a read-only view of the list
  4208. * @see Serializable
  4209. * @see RandomAccess
  4210. */
  4211. public static <T> List<T> unmodifiableList(List<? extends T> l)
  4212. {
  4213. if (l instanceof RandomAccess)
  4214. return new UnmodifiableRandomAccessList<T>(l);
  4215. return new UnmodifiableList<T>(l);
  4216. }
  4217. /**
  4218. * The implementation of {@link #unmodifiableList(List)} for sequential
  4219. * lists. This class name is required for compatibility with Sun's JDK
  4220. * serializability.
  4221. *
  4222. * @author Eric Blake (ebb9@email.byu.edu)
  4223. */
  4224. private static class UnmodifiableList<T> extends UnmodifiableCollection<T>
  4225. implements List<T>
  4226. {
  4227. /**
  4228. * Compatible with JDK 1.4.
  4229. */
  4230. private static final long serialVersionUID = -283967356065247728L;
  4231. /**
  4232. * The wrapped list; stored both here and in the superclass to avoid
  4233. * excessive casting. Package visible for use by subclass.
  4234. * @serial the wrapped list
  4235. */
  4236. final List<T> list;
  4237. /**
  4238. * Wrap a given list.
  4239. * @param l the list to wrap
  4240. * @throws NullPointerException if l is null
  4241. */
  4242. UnmodifiableList(List<? extends T> l)
  4243. {
  4244. super(l);
  4245. list = (List<T>) l;
  4246. }
  4247. /**
  4248. * Blocks the addition of an element to the underlying
  4249. * list at a specific index. This method never returns,
  4250. * throwing an exception instead.
  4251. *
  4252. * @param index The index at which to place the new element.
  4253. * @param o the object to add.
  4254. * @throws UnsupportedOperationException as an unmodifiable
  4255. * list doesn't support the <code>add()</code> operation.
  4256. */
  4257. public void add(int index, T o)
  4258. {
  4259. throw new UnsupportedOperationException();
  4260. }
  4261. /**
  4262. * Blocks the addition of a collection of elements to the
  4263. * underlying list at a specific index. This method never
  4264. * returns, throwing an exception instead.
  4265. *
  4266. * @param index The index at which to place the new element.
  4267. * @param c the collections of objects to add.
  4268. * @throws UnsupportedOperationException as an unmodifiable
  4269. * list doesn't support the <code>addAll()</code> operation.
  4270. */
  4271. public boolean addAll(int index, Collection<? extends T> c)
  4272. {
  4273. throw new UnsupportedOperationException();
  4274. }
  4275. /**
  4276. * Returns <code>true</code> if the object, o, is an instance of
  4277. * <code>List</code> with the same size and elements
  4278. * as the underlying list.
  4279. *
  4280. * @param o The object to compare.
  4281. * @return <code>true</code> if o is equivalent to the underlying list.
  4282. */
  4283. public boolean equals(Object o)
  4284. {
  4285. return list.equals(o);
  4286. }
  4287. /**
  4288. * Retrieves the element at a given index in the underlying list.
  4289. *
  4290. * @param index the index of the element to be returned
  4291. * @return the element at index index in this list
  4292. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  4293. */
  4294. public T get(int index)
  4295. {
  4296. return list.get(index);
  4297. }
  4298. /**
  4299. * Computes the hash code for the underlying list.
  4300. * The exact computation is described in the documentation
  4301. * of the <code>List</code> interface.
  4302. *
  4303. * @return The hash code of the underlying list.
  4304. * @see List#hashCode()
  4305. */
  4306. public int hashCode()
  4307. {
  4308. return list.hashCode();
  4309. }
  4310. /**
  4311. * Obtain the first index at which a given object is to be found in the
  4312. * underlying list.
  4313. *
  4314. * @param o the object to search for
  4315. * @return the least integer n such that <code>o == null ? get(n) == null :
  4316. * o.equals(get(n))</code>, or -1 if there is no such index.
  4317. * @throws ClassCastException if the type of o is not a valid
  4318. * type for the underlying list.
  4319. * @throws NullPointerException if o is null and the underlying
  4320. * list does not support null values.
  4321. */
  4322. public int indexOf(Object o)
  4323. {
  4324. return list.indexOf(o);
  4325. }
  4326. /**
  4327. * Obtain the last index at which a given object is to be found in the
  4328. * underlying list.
  4329. *
  4330. * @return the greatest integer n such that <code>o == null ? get(n) == null
  4331. * : o.equals(get(n))</code>, or -1 if there is no such index.
  4332. * @throws ClassCastException if the type of o is not a valid
  4333. * type for the underlying list.
  4334. * @throws NullPointerException if o is null and the underlying
  4335. * list does not support null values.
  4336. */
  4337. public int lastIndexOf(Object o)
  4338. {
  4339. return list.lastIndexOf(o);
  4340. }
  4341. /**
  4342. * Obtains a list iterator over the underlying list, starting at the beginning
  4343. * and maintaining the unmodifiable nature of this list.
  4344. *
  4345. * @return a <code>UnmodifiableListIterator</code> over the elements of the
  4346. * underlying list, in order, starting at the beginning.
  4347. */
  4348. public ListIterator<T> listIterator()
  4349. {
  4350. return new UnmodifiableListIterator<T>(list.listIterator());
  4351. }
  4352. /**
  4353. * Obtains a list iterator over the underlying list, starting at the specified
  4354. * index and maintaining the unmodifiable nature of this list. An initial call
  4355. * to <code>next()</code> will retrieve the element at the specified index,
  4356. * and an initial call to <code>previous()</code> will retrieve the element
  4357. * at index - 1.
  4358. *
  4359. *
  4360. * @param index the position, between 0 and size() inclusive, to begin the
  4361. * iteration from.
  4362. * @return a <code>UnmodifiableListIterator</code> over the elements of the
  4363. * underlying list, in order, starting at the specified index.
  4364. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  4365. */
  4366. public ListIterator<T> listIterator(int index)
  4367. {
  4368. return new UnmodifiableListIterator<T>(list.listIterator(index));
  4369. }
  4370. /**
  4371. * Blocks the removal of the element at the specified index.
  4372. * This method never returns, throwing an exception instead.
  4373. *
  4374. * @param index The index of the element to remove.
  4375. * @return the removed element.
  4376. * @throws UnsupportedOperationException as an unmodifiable
  4377. * list does not support the <code>remove()</code>
  4378. * operation.
  4379. */
  4380. public T remove(int index)
  4381. {
  4382. throw new UnsupportedOperationException();
  4383. }
  4384. /**
  4385. * Blocks the replacement of the element at the specified index.
  4386. * This method never returns, throwing an exception instead.
  4387. *
  4388. * @param index The index of the element to replace.
  4389. * @param o The new object to place at the specified index.
  4390. * @return the replaced element.
  4391. * @throws UnsupportedOperationException as an unmodifiable
  4392. * list does not support the <code>set()</code>
  4393. * operation.
  4394. */
  4395. public T set(int index, T o)
  4396. {
  4397. throw new UnsupportedOperationException();
  4398. }
  4399. /**
  4400. * Obtain a List view of a subsection of the underlying list, from
  4401. * fromIndex (inclusive) to toIndex (exclusive). If the two indices
  4402. * are equal, the sublist is empty. The returned list will be
  4403. * unmodifiable, like this list. Changes to the elements of the
  4404. * returned list will be reflected in the underlying list. No structural
  4405. * modifications can take place in either list.
  4406. *
  4407. * @param fromIndex the index that the returned list should start from
  4408. * (inclusive).
  4409. * @param toIndex the index that the returned list should go to (exclusive).
  4410. * @return a List backed by a subsection of the underlying list.
  4411. * @throws IndexOutOfBoundsException if fromIndex &lt; 0
  4412. * || toIndex &gt; size() || fromIndex &gt; toIndex.
  4413. */
  4414. public List<T> subList(int fromIndex, int toIndex)
  4415. {
  4416. return unmodifiableList(list.subList(fromIndex, toIndex));
  4417. }
  4418. } // class UnmodifiableList
  4419. /**
  4420. * The implementation of {@link #unmodifiableList(List)} for random-access
  4421. * lists. This class name is required for compatibility with Sun's JDK
  4422. * serializability.
  4423. *
  4424. * @author Eric Blake (ebb9@email.byu.edu)
  4425. */
  4426. private static final class UnmodifiableRandomAccessList<T>
  4427. extends UnmodifiableList<T> implements RandomAccess
  4428. {
  4429. /**
  4430. * Compatible with JDK 1.4.
  4431. */
  4432. private static final long serialVersionUID = -2542308836966382001L;
  4433. /**
  4434. * Wrap a given list.
  4435. * @param l the list to wrap
  4436. * @throws NullPointerException if l is null
  4437. */
  4438. UnmodifiableRandomAccessList(List<? extends T> l)
  4439. {
  4440. super(l);
  4441. }
  4442. } // class UnmodifiableRandomAccessList
  4443. /**
  4444. * The implementation of {@link UnmodifiableList#listIterator()}.
  4445. *
  4446. * @author Eric Blake (ebb9@email.byu.edu)
  4447. */
  4448. private static final class UnmodifiableListIterator<T>
  4449. extends UnmodifiableIterator<T> implements ListIterator<T>
  4450. {
  4451. /**
  4452. * The wrapped iterator, stored both here and in the superclass to
  4453. * avoid excessive casting.
  4454. */
  4455. private final ListIterator<T> li;
  4456. /**
  4457. * Only trusted code creates a wrapper.
  4458. * @param li the wrapped iterator
  4459. */
  4460. UnmodifiableListIterator(ListIterator<T> li)
  4461. {
  4462. super(li);
  4463. this.li = li;
  4464. }
  4465. /**
  4466. * Blocks the addition of an object to the list underlying this iterator.
  4467. * This method never returns, throwing an exception instead.
  4468. *
  4469. * @param o The object to add.
  4470. * @throws UnsupportedOperationException as the iterator of an unmodifiable
  4471. * list does not support the <code>add()</code> operation.
  4472. */
  4473. public void add(T o)
  4474. {
  4475. throw new UnsupportedOperationException();
  4476. }
  4477. /**
  4478. * Tests whether there are still elements to be retrieved from the
  4479. * underlying collection by <code>previous()</code>. When this method
  4480. * returns <code>true</code>, an exception will not be thrown on calling
  4481. * <code>previous()</code>.
  4482. *
  4483. * @return <code>true</code> if there is at least one more element prior to the
  4484. * current position in the underlying list.
  4485. */
  4486. public boolean hasPrevious()
  4487. {
  4488. return li.hasPrevious();
  4489. }
  4490. /**
  4491. * Find the index of the element that would be returned by a call to next.
  4492. * If <code>hasNext()</code> returns <code>false</code>, this returns the list size.
  4493. *
  4494. * @return the index of the element that would be returned by
  4495. * <code>next()</code>.
  4496. */
  4497. public int nextIndex()
  4498. {
  4499. return li.nextIndex();
  4500. }
  4501. /**
  4502. * Obtains the previous element in the underlying list.
  4503. *
  4504. * @return the previous element in the list.
  4505. * @throws NoSuchElementException if there are no more prior elements.
  4506. */
  4507. public T previous()
  4508. {
  4509. return li.previous();
  4510. }
  4511. /**
  4512. * Find the index of the element that would be returned by a call to
  4513. * previous. If <code>hasPrevious()</code> returns <code>false</code>,
  4514. * this returns -1.
  4515. *
  4516. * @return the index of the element that would be returned by
  4517. * <code>previous()</code>.
  4518. */
  4519. public int previousIndex()
  4520. {
  4521. return li.previousIndex();
  4522. }
  4523. /**
  4524. * Blocks the replacement of an element in the list underlying this
  4525. * iterator. This method never returns, throwing an exception instead.
  4526. *
  4527. * @param o The new object to replace the existing one.
  4528. * @throws UnsupportedOperationException as the iterator of an unmodifiable
  4529. * list does not support the <code>set()</code> operation.
  4530. */
  4531. public void set(T o)
  4532. {
  4533. throw new UnsupportedOperationException();
  4534. }
  4535. } // class UnmodifiableListIterator
  4536. /**
  4537. * Returns an unmodifiable view of the given map. This allows "read-only"
  4538. * access, although changes in the backing map show up in this view.
  4539. * Attempts to modify the map directly, or via collection views or their
  4540. * iterators will fail with {@link UnsupportedOperationException}.
  4541. * Although this view prevents changes to the structure of the map and its
  4542. * entries, the values referenced by the objects in the map can still be
  4543. * modified.
  4544. * <p>
  4545. *
  4546. * The returned Map implements Serializable, but can only be serialized if
  4547. * the map it wraps is likewise Serializable.
  4548. *
  4549. * @param m the map to wrap
  4550. * @return a read-only view of the map
  4551. * @see Serializable
  4552. */
  4553. public static <K, V> Map<K, V> unmodifiableMap(Map<? extends K,
  4554. ? extends V> m)
  4555. {
  4556. return new UnmodifiableMap<K, V>(m);
  4557. }
  4558. /**
  4559. * The implementation of {@link #unmodifiableMap(Map)}. This
  4560. * class name is required for compatibility with Sun's JDK serializability.
  4561. *
  4562. * @author Eric Blake (ebb9@email.byu.edu)
  4563. */
  4564. private static class UnmodifiableMap<K, V> implements Map<K, V>, Serializable
  4565. {
  4566. /**
  4567. * Compatible with JDK 1.4.
  4568. */
  4569. private static final long serialVersionUID = -1034234728574286014L;
  4570. /**
  4571. * The wrapped map.
  4572. * @serial the real map
  4573. */
  4574. private final Map<K, V> m;
  4575. /**
  4576. * Cache the entry set.
  4577. */
  4578. private transient Set<Map.Entry<K, V>> entries;
  4579. /**
  4580. * Cache the key set.
  4581. */
  4582. private transient Set<K> keys;
  4583. /**
  4584. * Cache the value collection.
  4585. */
  4586. private transient Collection<V> values;
  4587. /**
  4588. * Wrap a given map.
  4589. * @param m the map to wrap
  4590. * @throws NullPointerException if m is null
  4591. */
  4592. UnmodifiableMap(Map<? extends K, ? extends V> m)
  4593. {
  4594. this.m = (Map<K,V>) m;
  4595. if (m == null)
  4596. throw new NullPointerException();
  4597. }
  4598. /**
  4599. * Blocks the clearing of entries from the underlying map.
  4600. * This method never returns, throwing an exception instead.
  4601. *
  4602. * @throws UnsupportedOperationException as an unmodifiable
  4603. * map does not support the <code>clear()</code> operation.
  4604. */
  4605. public void clear()
  4606. {
  4607. throw new UnsupportedOperationException();
  4608. }
  4609. /**
  4610. * Returns <code>true</code> if the underlying map contains a mapping for
  4611. * the given key.
  4612. *
  4613. * @param key the key to search for
  4614. * @return <code>true</code> if the map contains the key
  4615. * @throws ClassCastException if the key is of an inappropriate type
  4616. * @throws NullPointerException if key is <code>null</code> but the map
  4617. * does not permit null keys
  4618. */
  4619. public boolean containsKey(Object key)
  4620. {
  4621. return m.containsKey(key);
  4622. }
  4623. /**
  4624. * Returns <code>true</code> if the underlying map contains at least one mapping with
  4625. * the given value. In other words, it returns <code>true</code> if a value v exists where
  4626. * <code>(value == null ? v == null : value.equals(v))</code>. This usually
  4627. * requires linear time.
  4628. *
  4629. * @param value the value to search for
  4630. * @return <code>true</code> if the map contains the value
  4631. * @throws ClassCastException if the type of the value is not a valid type
  4632. * for this map.
  4633. * @throws NullPointerException if the value is null and the map doesn't
  4634. * support null values.
  4635. */
  4636. public boolean containsValue(Object value)
  4637. {
  4638. return m.containsValue(value);
  4639. }
  4640. /**
  4641. * Returns a unmodifiable set view of the entries in the underlying map.
  4642. * Each element in the set is a unmodifiable variant of <code>Map.Entry</code>.
  4643. * The set is backed by the map, so that changes in one show up in the other.
  4644. * Modifications made while an iterator is in progress cause undefined
  4645. * behavior. These modifications are again limited to the values of
  4646. * the objects.
  4647. *
  4648. * @return the unmodifiable set view of all mapping entries.
  4649. * @see Map.Entry
  4650. */
  4651. public Set<Map.Entry<K, V>> entrySet()
  4652. {
  4653. if (entries == null)
  4654. entries = new UnmodifiableEntrySet<K,V>(m.entrySet());
  4655. return entries;
  4656. }
  4657. /**
  4658. * The implementation of {@link UnmodifiableMap#entrySet()}. This class
  4659. * name is required for compatibility with Sun's JDK serializability.
  4660. *
  4661. * @author Eric Blake (ebb9@email.byu.edu)
  4662. */
  4663. private static final class UnmodifiableEntrySet<K,V>
  4664. extends UnmodifiableSet<Map.Entry<K,V>>
  4665. implements Serializable
  4666. {
  4667. // Unmodifiable implementation of Map.Entry used as return value for
  4668. // UnmodifiableEntrySet accessors (iterator, toArray, toArray(Object[]))
  4669. private static final class UnmodifiableMapEntry<K,V>
  4670. implements Map.Entry<K,V>
  4671. {
  4672. private final Map.Entry<K,V> e;
  4673. private UnmodifiableMapEntry(Map.Entry<K,V> e)
  4674. {
  4675. super();
  4676. this.e = e;
  4677. }
  4678. /**
  4679. * Returns <code>true</code> if the object, o, is also a map entry
  4680. * with an identical key and value.
  4681. *
  4682. * @param o the object to compare.
  4683. * @return <code>true</code> if o is an equivalent map entry.
  4684. */
  4685. public boolean equals(Object o)
  4686. {
  4687. return e.equals(o);
  4688. }
  4689. /**
  4690. * Returns the key of this map entry.
  4691. *
  4692. * @return the key.
  4693. */
  4694. public K getKey()
  4695. {
  4696. return e.getKey();
  4697. }
  4698. /**
  4699. * Returns the value of this map entry.
  4700. *
  4701. * @return the value.
  4702. */
  4703. public V getValue()
  4704. {
  4705. return e.getValue();
  4706. }
  4707. /**
  4708. * Computes the hash code of this map entry. The computation is
  4709. * described in the <code>Map</code> interface documentation.
  4710. *
  4711. * @return the hash code of this entry.
  4712. * @see Map#hashCode()
  4713. */
  4714. public int hashCode()
  4715. {
  4716. return e.hashCode();
  4717. }
  4718. /**
  4719. * Blocks the alteration of the value of this map entry. This method
  4720. * never returns, throwing an exception instead.
  4721. *
  4722. * @param value The new value.
  4723. * @throws UnsupportedOperationException as an unmodifiable map entry
  4724. * does not support the <code>setValue()</code> operation.
  4725. */
  4726. public V setValue(V value)
  4727. {
  4728. throw new UnsupportedOperationException();
  4729. }
  4730. /**
  4731. * Returns a textual representation of the map entry.
  4732. *
  4733. * @return The map entry as a <code>String</code>.
  4734. */
  4735. public String toString()
  4736. {
  4737. return e.toString();
  4738. }
  4739. }
  4740. /**
  4741. * Compatible with JDK 1.4.
  4742. */
  4743. private static final long serialVersionUID = 7854390611657943733L;
  4744. /**
  4745. * Wrap a given set.
  4746. * @param s the set to wrap
  4747. */
  4748. UnmodifiableEntrySet(Set<Map.Entry<K,V>> s)
  4749. {
  4750. super(s);
  4751. }
  4752. // The iterator must return unmodifiable map entries.
  4753. public Iterator<Map.Entry<K,V>> iterator()
  4754. {
  4755. return new UnmodifiableIterator<Map.Entry<K,V>>(c.iterator())
  4756. {
  4757. /**
  4758. * Obtains the next element from the underlying set of
  4759. * map entries.
  4760. *
  4761. * @return the next element in the collection.
  4762. * @throws NoSuchElementException if there are no more elements.
  4763. */
  4764. public Map.Entry<K,V> next()
  4765. {
  4766. final Map.Entry<K,V> e = super.next();
  4767. return new UnmodifiableMapEntry<K,V>(e);
  4768. }
  4769. };
  4770. }
  4771. // The array returned is an array of UnmodifiableMapEntry instead of
  4772. // Map.Entry
  4773. public Object[] toArray()
  4774. {
  4775. Object[] mapEntryResult = super.toArray();
  4776. UnmodifiableMapEntry<K,V> result[] = null;
  4777. if (mapEntryResult != null)
  4778. {
  4779. result = (UnmodifiableMapEntry<K,V>[])
  4780. new UnmodifiableMapEntry[mapEntryResult.length];
  4781. for (int i = 0; i < mapEntryResult.length; ++i)
  4782. result[i] = new UnmodifiableMapEntry<K,V>((Map.Entry<K,V>)mapEntryResult[i]);
  4783. }
  4784. return result;
  4785. }
  4786. // The array returned is an array of UnmodifiableMapEntry instead of
  4787. // Map.Entry
  4788. public <S> S[] toArray(S[] array)
  4789. {
  4790. S[] result = super.toArray(array);
  4791. if (result != null)
  4792. for (int i = 0; i < result.length; i++)
  4793. array[i] =
  4794. (S) new UnmodifiableMapEntry<K,V>((Map.Entry<K,V>) result[i]);
  4795. return array;
  4796. }
  4797. } // class UnmodifiableEntrySet
  4798. /**
  4799. * Returns <code>true</code> if the object, o, is also an instance
  4800. * of <code>Map</code> with an equal set of map entries.
  4801. *
  4802. * @param o The object to compare.
  4803. * @return <code>true</code> if o is an equivalent map.
  4804. */
  4805. public boolean equals(Object o)
  4806. {
  4807. return m.equals(o);
  4808. }
  4809. /**
  4810. * Returns the value associated with the supplied key or
  4811. * null if no such mapping exists. An ambiguity can occur
  4812. * if null values are accepted by the underlying map.
  4813. * In this case, <code>containsKey()</code> can be used
  4814. * to separate the two possible cases of a null result.
  4815. *
  4816. * @param key The key to look up.
  4817. * @return the value associated with the key, or null if key not in map.
  4818. * @throws ClassCastException if the key is an inappropriate type.
  4819. * @throws NullPointerException if this map does not accept null keys.
  4820. * @see #containsKey(Object)
  4821. */
  4822. public V get(Object key)
  4823. {
  4824. return m.get(key);
  4825. }
  4826. /**
  4827. * Blocks the addition of a new entry to the underlying map.
  4828. * This method never returns, throwing an exception instead.
  4829. *
  4830. * @param key The new key.
  4831. * @param value The new value.
  4832. * @return the previous value of the key, or null if there was no mapping.
  4833. * @throws UnsupportedOperationException as an unmodifiable
  4834. * map does not support the <code>put()</code> operation.
  4835. */
  4836. public V put(K key, V value)
  4837. {
  4838. throw new UnsupportedOperationException();
  4839. }
  4840. /**
  4841. * Computes the hash code for the underlying map, as the sum
  4842. * of the hash codes of all entries.
  4843. *
  4844. * @return The hash code of the underlying map.
  4845. * @see Map.Entry#hashCode()
  4846. */
  4847. public int hashCode()
  4848. {
  4849. return m.hashCode();
  4850. }
  4851. /**
  4852. * Returns <code>true</code> if the underlying map contains no entries.
  4853. *
  4854. * @return <code>true</code> if the map is empty.
  4855. */
  4856. public boolean isEmpty()
  4857. {
  4858. return m.isEmpty();
  4859. }
  4860. /**
  4861. * Returns a unmodifiable set view of the keys in the underlying map.
  4862. * The set is backed by the map, so that changes in one show up in the other.
  4863. * Modifications made while an iterator is in progress cause undefined
  4864. * behavior. These modifications are again limited to the values of
  4865. * the keys.
  4866. *
  4867. * @return the set view of all keys.
  4868. */
  4869. public Set<K> keySet()
  4870. {
  4871. if (keys == null)
  4872. keys = new UnmodifiableSet<K>(m.keySet());
  4873. return keys;
  4874. }
  4875. /**
  4876. * Blocks the addition of the entries in the supplied map.
  4877. * This method never returns, throwing an exception instead.
  4878. *
  4879. * @param m The map, the entries of which should be added
  4880. * to the underlying map.
  4881. * @throws UnsupportedOperationException as an unmodifiable
  4882. * map does not support the <code>putAll</code> operation.
  4883. */
  4884. public void putAll(Map<? extends K, ? extends V> m)
  4885. {
  4886. throw new UnsupportedOperationException();
  4887. }
  4888. /**
  4889. * Blocks the removal of an entry from the map.
  4890. * This method never returns, throwing an exception instead.
  4891. *
  4892. * @param o The key of the entry to remove.
  4893. * @return The value the key was associated with, or null
  4894. * if no such mapping existed. Null is also returned
  4895. * if the removed entry had a null key.
  4896. * @throws UnsupportedOperationException as an unmodifiable
  4897. * map does not support the <code>remove</code> operation.
  4898. */
  4899. public V remove(Object o)
  4900. {
  4901. throw new UnsupportedOperationException();
  4902. }
  4903. /**
  4904. * Returns the number of key-value mappings in the underlying map.
  4905. * If there are more than Integer.MAX_VALUE mappings, Integer.MAX_VALUE
  4906. * is returned.
  4907. *
  4908. * @return the number of mappings.
  4909. */
  4910. public int size()
  4911. {
  4912. return m.size();
  4913. }
  4914. /**
  4915. * Returns a textual representation of the map.
  4916. *
  4917. * @return The map in the form of a <code>String</code>.
  4918. */
  4919. public String toString()
  4920. {
  4921. return m.toString();
  4922. }
  4923. /**
  4924. * Returns a unmodifiable collection view of the values in the underlying map.
  4925. * The collection is backed by the map, so that changes in one show up in the other.
  4926. * Modifications made while an iterator is in progress cause undefined
  4927. * behavior. These modifications are again limited to the values of
  4928. * the keys.
  4929. *
  4930. * @return the collection view of all values.
  4931. */
  4932. public Collection<V> values()
  4933. {
  4934. if (values == null)
  4935. values = new UnmodifiableCollection<V>(m.values());
  4936. return values;
  4937. }
  4938. } // class UnmodifiableMap
  4939. /**
  4940. * Returns an unmodifiable view of the given set. This allows
  4941. * "read-only" access, although changes in the backing set show up
  4942. * in this view. Attempts to modify the set directly or via iterators
  4943. * will fail with {@link UnsupportedOperationException}.
  4944. * Although this view prevents changes to the structure of the set and its
  4945. * entries, the values referenced by the objects in the set can still be
  4946. * modified.
  4947. * <p>
  4948. *
  4949. * The returned Set implements Serializable, but can only be serialized if
  4950. * the set it wraps is likewise Serializable.
  4951. *
  4952. * @param s the set to wrap
  4953. * @return a read-only view of the set
  4954. * @see Serializable
  4955. */
  4956. public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
  4957. {
  4958. return new UnmodifiableSet<T>(s);
  4959. }
  4960. /**
  4961. * The implementation of {@link #unmodifiableSet(Set)}. This class
  4962. * name is required for compatibility with Sun's JDK serializability.
  4963. *
  4964. * @author Eric Blake (ebb9@email.byu.edu)
  4965. */
  4966. private static class UnmodifiableSet<T> extends UnmodifiableCollection<T>
  4967. implements Set<T>
  4968. {
  4969. /**
  4970. * Compatible with JDK 1.4.
  4971. */
  4972. private static final long serialVersionUID = -9215047833775013803L;
  4973. /**
  4974. * Wrap a given set.
  4975. * @param s the set to wrap
  4976. * @throws NullPointerException if s is null
  4977. */
  4978. UnmodifiableSet(Set<? extends T> s)
  4979. {
  4980. super(s);
  4981. }
  4982. /**
  4983. * Returns <code>true</code> if the object, o, is also an instance of
  4984. * <code>Set</code> of the same size and with the same entries.
  4985. *
  4986. * @return <code>true</code> if o is an equivalent set.
  4987. */
  4988. public boolean equals(Object o)
  4989. {
  4990. return c.equals(o);
  4991. }
  4992. /**
  4993. * Computes the hash code of this set, as the sum of the
  4994. * hash codes of all elements within the set.
  4995. *
  4996. * @return the hash code of the set.
  4997. */
  4998. public int hashCode()
  4999. {
  5000. return c.hashCode();
  5001. }
  5002. } // class UnmodifiableSet
  5003. /**
  5004. * Returns an unmodifiable view of the given sorted map. This allows
  5005. * "read-only" access, although changes in the backing map show up in this
  5006. * view. Attempts to modify the map directly, via subviews, via collection
  5007. * views, or iterators, will fail with {@link UnsupportedOperationException}.
  5008. * Although this view prevents changes to the structure of the map and its
  5009. * entries, the values referenced by the objects in the map can still be
  5010. * modified.
  5011. * <p>
  5012. *
  5013. * The returned SortedMap implements Serializable, but can only be
  5014. * serialized if the map it wraps is likewise Serializable.
  5015. *
  5016. * @param m the map to wrap
  5017. * @return a read-only view of the map
  5018. * @see Serializable
  5019. */
  5020. public static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K,
  5021. ? extends V> m)
  5022. {
  5023. return new UnmodifiableSortedMap<K, V>(m);
  5024. }
  5025. /**
  5026. * The implementation of {@link #unmodifiableSortedMap(SortedMap)}. This
  5027. * class name is required for compatibility with Sun's JDK serializability.
  5028. *
  5029. * @author Eric Blake (ebb9@email.byu.edu)
  5030. */
  5031. private static class UnmodifiableSortedMap<K, V>
  5032. extends UnmodifiableMap<K, V>
  5033. implements SortedMap<K, V>
  5034. {
  5035. /**
  5036. * Compatible with JDK 1.4.
  5037. */
  5038. private static final long serialVersionUID = -8806743815996713206L;
  5039. /**
  5040. * The wrapped map; stored both here and in the superclass to avoid
  5041. * excessive casting.
  5042. * @serial the wrapped map
  5043. */
  5044. private final SortedMap<K, V> sm;
  5045. /**
  5046. * Wrap a given map.
  5047. * @param sm the map to wrap
  5048. * @throws NullPointerException if sm is null
  5049. */
  5050. UnmodifiableSortedMap(SortedMap<K, ? extends V> sm)
  5051. {
  5052. super(sm);
  5053. this.sm = (SortedMap<K,V>) sm;
  5054. }
  5055. /**
  5056. * Returns the comparator used in sorting the underlying map,
  5057. * or null if it is the keys' natural ordering.
  5058. *
  5059. * @return the sorting comparator.
  5060. */
  5061. public Comparator<? super K> comparator()
  5062. {
  5063. return sm.comparator();
  5064. }
  5065. /**
  5066. * Returns the first (lowest sorted) key in the map.
  5067. *
  5068. * @return the first key.
  5069. * @throws NoSuchElementException if this map is empty.
  5070. */
  5071. public K firstKey()
  5072. {
  5073. return sm.firstKey();
  5074. }
  5075. /**
  5076. * Returns a unmodifiable view of the portion of the map strictly less
  5077. * than toKey. The view is backed by the underlying map, so changes in
  5078. * one show up in the other. The submap supports all optional operations
  5079. * of the original. This operation is equivalent to
  5080. * <code>subMap(firstKey(), toKey)</code>.
  5081. * <p>
  5082. *
  5083. * The returned map throws an IllegalArgumentException any time a key is
  5084. * used which is out of the range of toKey. Note that the endpoint, toKey,
  5085. * is not included; if you want this value to be included, pass its successor
  5086. * object in to toKey. For example, for Integers, you could request
  5087. * <code>headMap(new Integer(limit.intValue() + 1))</code>.
  5088. *
  5089. * @param toKey the exclusive upper range of the submap.
  5090. * @return the submap.
  5091. * @throws ClassCastException if toKey is not comparable to the map contents.
  5092. * @throws IllegalArgumentException if this is a subMap, and toKey is out
  5093. * of range.
  5094. * @throws NullPointerException if toKey is null but the map does not allow
  5095. * null keys.
  5096. */
  5097. public SortedMap<K, V> headMap(K toKey)
  5098. {
  5099. return new UnmodifiableSortedMap<K, V>(sm.headMap(toKey));
  5100. }
  5101. /**
  5102. * Returns the last (highest sorted) key in the map.
  5103. *
  5104. * @return the last key.
  5105. * @throws NoSuchElementException if this map is empty.
  5106. */
  5107. public K lastKey()
  5108. {
  5109. return sm.lastKey();
  5110. }
  5111. /**
  5112. * Returns a unmodifiable view of the portion of the map greater than or
  5113. * equal to fromKey, and strictly less than toKey. The view is backed by
  5114. * the underlying map, so changes in one show up in the other. The submap
  5115. * supports all optional operations of the original.
  5116. * <p>
  5117. *
  5118. * The returned map throws an IllegalArgumentException any time a key is
  5119. * used which is out of the range of fromKey and toKey. Note that the
  5120. * lower endpoint is included, but the upper is not; if you want to
  5121. * change the inclusion or exclusion of an endpoint, pass its successor
  5122. * object in instead. For example, for Integers, you could request
  5123. * <code>subMap(new Integer(lowlimit.intValue() + 1),
  5124. * new Integer(highlimit.intValue() + 1))</code> to reverse
  5125. * the inclusiveness of both endpoints.
  5126. *
  5127. * @param fromKey the inclusive lower range of the submap.
  5128. * @param toKey the exclusive upper range of the submap.
  5129. * @return the submap.
  5130. * @throws ClassCastException if fromKey or toKey is not comparable to
  5131. * the map contents.
  5132. * @throws IllegalArgumentException if this is a subMap, and fromKey or
  5133. * toKey is out of range.
  5134. * @throws NullPointerException if fromKey or toKey is null but the map
  5135. * does not allow null keys.
  5136. */
  5137. public SortedMap<K, V> subMap(K fromKey, K toKey)
  5138. {
  5139. return new UnmodifiableSortedMap<K, V>(sm.subMap(fromKey, toKey));
  5140. }
  5141. /**
  5142. * Returns a unmodifiable view of the portion of the map greater than or
  5143. * equal to fromKey. The view is backed by the underlying map, so changes
  5144. * in one show up in the other. The submap supports all optional operations
  5145. * of the original.
  5146. * <p>
  5147. *
  5148. * The returned map throws an IllegalArgumentException any time a key is
  5149. * used which is out of the range of fromKey. Note that the endpoint, fromKey, is
  5150. * included; if you do not want this value to be included, pass its successor object in
  5151. * to fromKey. For example, for Integers, you could request
  5152. * <code>tailMap(new Integer(limit.intValue() + 1))</code>.
  5153. *
  5154. * @param fromKey the inclusive lower range of the submap
  5155. * @return the submap
  5156. * @throws ClassCastException if fromKey is not comparable to the map
  5157. * contents
  5158. * @throws IllegalArgumentException if this is a subMap, and fromKey is out
  5159. * of range
  5160. * @throws NullPointerException if fromKey is null but the map does not allow
  5161. * null keys
  5162. */
  5163. public SortedMap<K, V> tailMap(K fromKey)
  5164. {
  5165. return new UnmodifiableSortedMap<K, V>(sm.tailMap(fromKey));
  5166. }
  5167. } // class UnmodifiableSortedMap
  5168. /**
  5169. * Returns an unmodifiable view of the given sorted set. This allows
  5170. * "read-only" access, although changes in the backing set show up
  5171. * in this view. Attempts to modify the set directly, via subsets, or via
  5172. * iterators, will fail with {@link UnsupportedOperationException}.
  5173. * Although this view prevents changes to the structure of the set and its
  5174. * entries, the values referenced by the objects in the set can still be
  5175. * modified.
  5176. * <p>
  5177. *
  5178. * The returns SortedSet implements Serializable, but can only be
  5179. * serialized if the set it wraps is likewise Serializable.
  5180. *
  5181. * @param s the set to wrap
  5182. * @return a read-only view of the set
  5183. * @see Serializable
  5184. */
  5185. public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
  5186. {
  5187. return new UnmodifiableSortedSet<T>(s);
  5188. }
  5189. /**
  5190. * The implementation of {@link #synchronizedSortedMap(SortedMap)}. This
  5191. * class name is required for compatibility with Sun's JDK serializability.
  5192. *
  5193. * @author Eric Blake (ebb9@email.byu.edu)
  5194. */
  5195. private static class UnmodifiableSortedSet<T> extends UnmodifiableSet<T>
  5196. implements SortedSet<T>
  5197. {
  5198. /**
  5199. * Compatible with JDK 1.4.
  5200. */
  5201. private static final long serialVersionUID = -4929149591599911165L;
  5202. /**
  5203. * The wrapped set; stored both here and in the superclass to avoid
  5204. * excessive casting.
  5205. * @serial the wrapped set
  5206. */
  5207. private SortedSet<T> ss;
  5208. /**
  5209. * Wrap a given set.
  5210. * @param ss the set to wrap
  5211. * @throws NullPointerException if ss is null
  5212. */
  5213. UnmodifiableSortedSet(SortedSet<T> ss)
  5214. {
  5215. super(ss);
  5216. this.ss = ss;
  5217. }
  5218. /**
  5219. * Returns the comparator used in sorting the underlying set,
  5220. * or null if it is the elements' natural ordering.
  5221. *
  5222. * @return the sorting comparator
  5223. */
  5224. public Comparator<? super T> comparator()
  5225. {
  5226. return ss.comparator();
  5227. }
  5228. /**
  5229. * Returns the first (lowest sorted) element in the underlying
  5230. * set.
  5231. *
  5232. * @return the first element.
  5233. * @throws NoSuchElementException if the set is empty.
  5234. */
  5235. public T first()
  5236. {
  5237. return ss.first();
  5238. }
  5239. /**
  5240. * Returns a unmodifiable view of the portion of the set strictly
  5241. * less than toElement. The view is backed by the underlying set,
  5242. * so changes in one show up in the other. The subset supports
  5243. * all optional operations of the original. This operation
  5244. * is equivalent to <code>subSet(first(), toElement)</code>.
  5245. * <p>
  5246. *
  5247. * The returned set throws an IllegalArgumentException any time an element is
  5248. * used which is out of the range of toElement. Note that the endpoint, toElement,
  5249. * is not included; if you want this value included, pass its successor object in to
  5250. * toElement. For example, for Integers, you could request
  5251. * <code>headSet(new Integer(limit.intValue() + 1))</code>.
  5252. *
  5253. * @param toElement the exclusive upper range of the subset
  5254. * @return the subset.
  5255. * @throws ClassCastException if toElement is not comparable to the set
  5256. * contents.
  5257. * @throws IllegalArgumentException if this is a subSet, and toElement is out
  5258. * of range.
  5259. * @throws NullPointerException if toElement is null but the set does not
  5260. * allow null elements.
  5261. */
  5262. public SortedSet<T> headSet(T toElement)
  5263. {
  5264. return new UnmodifiableSortedSet<T>(ss.headSet(toElement));
  5265. }
  5266. /**
  5267. * Returns the last (highest sorted) element in the underlying
  5268. * set.
  5269. *
  5270. * @return the last element.
  5271. * @throws NoSuchElementException if the set is empty.
  5272. */
  5273. public T last()
  5274. {
  5275. return ss.last();
  5276. }
  5277. /**
  5278. * Returns a unmodifiable view of the portion of the set greater than or
  5279. * equal to fromElement, and strictly less than toElement. The view is backed by
  5280. * the underlying set, so changes in one show up in the other. The subset
  5281. * supports all optional operations of the original.
  5282. * <p>
  5283. *
  5284. * The returned set throws an IllegalArgumentException any time an element is
  5285. * used which is out of the range of fromElement and toElement. Note that the
  5286. * lower endpoint is included, but the upper is not; if you want to
  5287. * change the inclusion or exclusion of an endpoint, pass its successor
  5288. * object in instead. For example, for Integers, you can request
  5289. * <code>subSet(new Integer(lowlimit.intValue() + 1),
  5290. * new Integer(highlimit.intValue() + 1))</code> to reverse
  5291. * the inclusiveness of both endpoints.
  5292. *
  5293. * @param fromElement the inclusive lower range of the subset.
  5294. * @param toElement the exclusive upper range of the subset.
  5295. * @return the subset.
  5296. * @throws ClassCastException if fromElement or toElement is not comparable
  5297. * to the set contents.
  5298. * @throws IllegalArgumentException if this is a subSet, and fromElement or
  5299. * toElement is out of range.
  5300. * @throws NullPointerException if fromElement or toElement is null but the
  5301. * set does not allow null elements.
  5302. */
  5303. public SortedSet<T> subSet(T fromElement, T toElement)
  5304. {
  5305. return new UnmodifiableSortedSet<T>(ss.subSet(fromElement, toElement));
  5306. }
  5307. /**
  5308. * Returns a unmodifiable view of the portion of the set greater than or equal to
  5309. * fromElement. The view is backed by the underlying set, so changes in one show up
  5310. * in the other. The subset supports all optional operations of the original.
  5311. * <p>
  5312. *
  5313. * The returned set throws an IllegalArgumentException any time an element is
  5314. * used which is out of the range of fromElement. Note that the endpoint,
  5315. * fromElement, is included; if you do not want this value to be included, pass its
  5316. * successor object in to fromElement. For example, for Integers, you could request
  5317. * <code>tailSet(new Integer(limit.intValue() + 1))</code>.
  5318. *
  5319. * @param fromElement the inclusive lower range of the subset
  5320. * @return the subset.
  5321. * @throws ClassCastException if fromElement is not comparable to the set
  5322. * contents.
  5323. * @throws IllegalArgumentException if this is a subSet, and fromElement is
  5324. * out of range.
  5325. * @throws NullPointerException if fromElement is null but the set does not
  5326. * allow null elements.
  5327. */
  5328. public SortedSet<T> tailSet(T fromElement)
  5329. {
  5330. return new UnmodifiableSortedSet<T>(ss.tailSet(fromElement));
  5331. }
  5332. } // class UnmodifiableSortedSet
  5333. /**
  5334. * <p>
  5335. * Returns a dynamically typesafe view of the given collection,
  5336. * where any modification is first checked to ensure that the type
  5337. * of the new data is appropriate. Although the addition of
  5338. * generics and parametrically-typed collections prevents an
  5339. * incorrect type of element being added to a collection at
  5340. * compile-time, via static type checking, this can be overridden by
  5341. * casting. In contrast, wrapping the collection within a
  5342. * dynamically-typesafe wrapper, using this and associated methods,
  5343. * <emph>guarantees</emph> that the collection will only contain
  5344. * elements of an appropriate type (provided it only contains such
  5345. * at the type of wrapping, and all subsequent access is via the
  5346. * wrapper). This can be useful for debugging the cause of a
  5347. * <code>ClassCastException</code> caused by erroneous casting, or
  5348. * for protecting collections from corruption by external libraries.
  5349. * </p>
  5350. * <p>
  5351. * Since the collection might be a List or a Set, and those
  5352. * have incompatible equals and hashCode requirements, this relies
  5353. * on Object's implementation rather than passing those calls on to
  5354. * the wrapped collection. The returned Collection implements
  5355. * Serializable, but can only be serialized if the collection it
  5356. * wraps is likewise Serializable.
  5357. * </p>
  5358. *
  5359. * @param c the collection to wrap in a dynamically typesafe wrapper
  5360. * @param type the type of elements the collection should hold.
  5361. * @return a dynamically typesafe view of the collection.
  5362. * @see Serializable
  5363. * @since 1.5
  5364. */
  5365. public static <E> Collection<E> checkedCollection(Collection<E> c,
  5366. Class<E> type)
  5367. {
  5368. return new CheckedCollection<E>(c, type);
  5369. }
  5370. /**
  5371. * The implementation of {@link #checkedCollection(Collection,Class)}. This
  5372. * class name is required for compatibility with Sun's JDK serializability.
  5373. *
  5374. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  5375. * @since 1.5
  5376. */
  5377. private static class CheckedCollection<E>
  5378. implements Collection<E>, Serializable
  5379. {
  5380. /**
  5381. * Compatible with JDK 1.5.
  5382. */
  5383. private static final long serialVersionUID = 1578914078182001775L;
  5384. /**
  5385. * The wrapped collection. Package visible for use by subclasses.
  5386. * @serial the real collection
  5387. */
  5388. final Collection<E> c;
  5389. /**
  5390. * The type of the elements of this collection.
  5391. * @serial the element type.
  5392. */
  5393. final Class<E> type;
  5394. /**
  5395. * Wrap a given collection.
  5396. * @param c the collection to wrap
  5397. * @param type the type to wrap
  5398. * @throws NullPointerException if c is null
  5399. */
  5400. CheckedCollection(Collection<E> c, Class<E> type)
  5401. {
  5402. this.c = c;
  5403. this.type = type;
  5404. if (c == null)
  5405. throw new NullPointerException();
  5406. }
  5407. /**
  5408. * Adds the supplied object to the collection, on the condition that
  5409. * it is of the correct type.
  5410. *
  5411. * @param o the object to add.
  5412. * @return <code>true</code> if the collection was modified as a result
  5413. * of this action.
  5414. * @throws ClassCastException if the object is not of the correct type.
  5415. */
  5416. public boolean add(E o)
  5417. {
  5418. if (type.isInstance(o))
  5419. return c.add(o);
  5420. else
  5421. throw new ClassCastException("The element is of the incorrect type.");
  5422. }
  5423. /**
  5424. * Adds the elements of the specified collection to the backing collection,
  5425. * provided they are all of the correct type.
  5426. *
  5427. * @param coll the collection to add.
  5428. * @return <code>true</code> if the collection was modified as a result
  5429. * of this action.
  5430. * @throws ClassCastException if <code>c</code> contained elements of an
  5431. * incorrect type.
  5432. */
  5433. public boolean addAll(Collection<? extends E> coll)
  5434. {
  5435. Collection<E> typedColl = (Collection<E>) c;
  5436. final Iterator<E> it = typedColl.iterator();
  5437. while (it.hasNext())
  5438. {
  5439. final E element = it.next();
  5440. if (!type.isInstance(element))
  5441. throw new ClassCastException("A member of the collection is not of the correct type.");
  5442. }
  5443. return c.addAll(typedColl);
  5444. }
  5445. /**
  5446. * Removes all elements from the underlying collection.
  5447. */
  5448. public void clear()
  5449. {
  5450. c.clear();
  5451. }
  5452. /**
  5453. * Test whether the underlying collection contains a given object as one
  5454. * of its elements.
  5455. *
  5456. * @param o the element to look for.
  5457. * @return <code>true</code> if the underlying collection contains at least
  5458. * one element e such that
  5459. * <code>o == null ? e == null : o.equals(e)</code>.
  5460. * @throws ClassCastException if the type of o is not a valid type for the
  5461. * underlying collection.
  5462. * @throws NullPointerException if o is null and the underlying collection
  5463. * doesn't support null values.
  5464. */
  5465. public boolean contains(Object o)
  5466. {
  5467. return c.contains(o);
  5468. }
  5469. /**
  5470. * Test whether the underlying collection contains every element in a given
  5471. * collection.
  5472. *
  5473. * @param coll the collection to test for.
  5474. * @return <code>true</code> if for every element o in c, contains(o) would
  5475. * return <code>true</code>.
  5476. * @throws ClassCastException if the type of any element in c is not a
  5477. * valid type for the underlying collection.
  5478. * @throws NullPointerException if some element of c is null and the
  5479. * underlying collection does not support
  5480. * null values.
  5481. * @throws NullPointerException if c itself is null.
  5482. */
  5483. public boolean containsAll(Collection<?> coll)
  5484. {
  5485. return c.containsAll(coll);
  5486. }
  5487. /**
  5488. * Tests whether the underlying collection is empty, that is,
  5489. * if size() == 0.
  5490. *
  5491. * @return <code>true</code> if this collection contains no elements.
  5492. */
  5493. public boolean isEmpty()
  5494. {
  5495. return c.isEmpty();
  5496. }
  5497. /**
  5498. * Obtain an Iterator over the underlying collection, which maintains
  5499. * its checked nature.
  5500. *
  5501. * @return a Iterator over the elements of the underlying
  5502. * collection, in any order.
  5503. */
  5504. public Iterator<E> iterator()
  5505. {
  5506. return new CheckedIterator<E>(c.iterator(), type);
  5507. }
  5508. /**
  5509. * Removes the supplied object from the collection, if it exists.
  5510. *
  5511. * @param o The object to remove.
  5512. * @return <code>true</code> if the object was removed (i.e. the underlying
  5513. * collection returned 1 or more instances of o).
  5514. */
  5515. public boolean remove(Object o)
  5516. {
  5517. return c.remove(o);
  5518. }
  5519. /**
  5520. * Removes all objects in the supplied collection from the backing
  5521. * collection, if they exist within it.
  5522. *
  5523. * @param coll the collection of objects to remove.
  5524. * @return <code>true</code> if the collection was modified.
  5525. */
  5526. public boolean removeAll(Collection<?> coll)
  5527. {
  5528. return c.removeAll(coll);
  5529. }
  5530. /**
  5531. * Retains all objects specified by the supplied collection which exist
  5532. * within the backing collection, and removes all others.
  5533. *
  5534. * @param coll the collection of objects to retain.
  5535. * @return <code>true</code> if the collection was modified.
  5536. */
  5537. public boolean retainAll(Collection<?> coll)
  5538. {
  5539. return c.retainAll(coll);
  5540. }
  5541. /**
  5542. * Retrieves the number of elements in the underlying collection.
  5543. *
  5544. * @return the number of elements in the collection.
  5545. */
  5546. public int size()
  5547. {
  5548. return c.size();
  5549. }
  5550. /**
  5551. * Copy the current contents of the underlying collection into an array.
  5552. *
  5553. * @return an array of type Object[] with a length equal to the size of the
  5554. * underlying collection and containing the elements currently in
  5555. * the underlying collection, in any order.
  5556. */
  5557. public Object[] toArray()
  5558. {
  5559. return c.toArray();
  5560. }
  5561. /**
  5562. * <p>
  5563. * Copy the current contents of the underlying collection into an array. If
  5564. * the array passed as an argument has length less than the size of the
  5565. * underlying collection, an array of the same run-time type as a, with a
  5566. * length equal to the size of the underlying collection, is allocated
  5567. * using reflection.
  5568. * </p>
  5569. * <p>
  5570. * Otherwise, a itself is used. The elements of the underlying collection
  5571. * are copied into it, and if there is space in the array, the following
  5572. * element is set to null. The resultant array is returned.
  5573. * </p>
  5574. * <p>
  5575. * <emph>Note</emph>: The fact that the following element is set to null
  5576. * is only useful if it is known that this collection does not contain
  5577. * any null elements.
  5578. *
  5579. * @param a the array to copy this collection into.
  5580. * @return an array containing the elements currently in the underlying
  5581. * collection, in any order.
  5582. * @throws ArrayStoreException if the type of any element of the
  5583. * collection is not a subtype of the element type of a.
  5584. */
  5585. public <S> S[] toArray(S[] a)
  5586. {
  5587. return c.toArray(a);
  5588. }
  5589. /**
  5590. * A textual representation of the unmodifiable collection.
  5591. *
  5592. * @return The checked collection in the form of a <code>String</code>.
  5593. */
  5594. public String toString()
  5595. {
  5596. return c.toString();
  5597. }
  5598. } // class CheckedCollection
  5599. /**
  5600. * The implementation of the various iterator methods in the
  5601. * checked classes.
  5602. *
  5603. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  5604. * @since 1.5
  5605. */
  5606. private static class CheckedIterator<E>
  5607. implements Iterator<E>
  5608. {
  5609. /**
  5610. * The wrapped iterator.
  5611. */
  5612. private final Iterator<E> i;
  5613. /**
  5614. * The type of the elements of this collection.
  5615. * @serial the element type.
  5616. */
  5617. final Class<E> type;
  5618. /**
  5619. * Only trusted code creates a wrapper.
  5620. * @param i the wrapped iterator
  5621. * @param type the type of the elements within the checked list.
  5622. */
  5623. CheckedIterator(Iterator<E> i, Class<E> type)
  5624. {
  5625. this.i = i;
  5626. this.type = type;
  5627. }
  5628. /**
  5629. * Obtains the next element in the underlying collection.
  5630. *
  5631. * @return the next element in the collection.
  5632. * @throws NoSuchElementException if there are no more elements.
  5633. */
  5634. public E next()
  5635. {
  5636. return i.next();
  5637. }
  5638. /**
  5639. * Tests whether there are still elements to be retrieved from the
  5640. * underlying collection by <code>next()</code>. When this method
  5641. * returns <code>true</code>, an exception will not be thrown on calling
  5642. * <code>next()</code>.
  5643. *
  5644. * @return <code>true</code> if there is at least one more element in the
  5645. * underlying collection.
  5646. */
  5647. public boolean hasNext()
  5648. {
  5649. return i.hasNext();
  5650. }
  5651. /**
  5652. * Removes the next element from the collection.
  5653. */
  5654. public void remove()
  5655. {
  5656. i.remove();
  5657. }
  5658. } // class CheckedIterator
  5659. /**
  5660. * <p>
  5661. * Returns a dynamically typesafe view of the given list,
  5662. * where any modification is first checked to ensure that the type
  5663. * of the new data is appropriate. Although the addition of
  5664. * generics and parametrically-typed collections prevents an
  5665. * incorrect type of element being added to a collection at
  5666. * compile-time, via static type checking, this can be overridden by
  5667. * casting. In contrast, wrapping the collection within a
  5668. * dynamically-typesafe wrapper, using this and associated methods,
  5669. * <emph>guarantees</emph> that the collection will only contain
  5670. * elements of an appropriate type (provided it only contains such
  5671. * at the type of wrapping, and all subsequent access is via the
  5672. * wrapper). This can be useful for debugging the cause of a
  5673. * <code>ClassCastException</code> caused by erroneous casting, or
  5674. * for protecting collections from corruption by external libraries.
  5675. * </p>
  5676. * <p>
  5677. * The returned List implements Serializable, but can only be serialized if
  5678. * the list it wraps is likewise Serializable. In addition, if the wrapped
  5679. * list implements RandomAccess, this does too.
  5680. * </p>
  5681. *
  5682. * @param l the list to wrap
  5683. * @param type the type of the elements within the checked list.
  5684. * @return a dynamically typesafe view of the list
  5685. * @see Serializable
  5686. * @see RandomAccess
  5687. */
  5688. public static <E> List<E> checkedList(List<E> l, Class<E> type)
  5689. {
  5690. if (l instanceof RandomAccess)
  5691. return new CheckedRandomAccessList<E>(l, type);
  5692. return new CheckedList<E>(l, type);
  5693. }
  5694. /**
  5695. * The implementation of {@link #checkedList(List,Class)} for sequential
  5696. * lists. This class name is required for compatibility with Sun's JDK
  5697. * serializability.
  5698. *
  5699. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  5700. * @since 1.5
  5701. */
  5702. private static class CheckedList<E>
  5703. extends CheckedCollection<E>
  5704. implements List<E>
  5705. {
  5706. /**
  5707. * Compatible with JDK 1.5.
  5708. */
  5709. private static final long serialVersionUID = 65247728283967356L;
  5710. /**
  5711. * The wrapped list; stored both here and in the superclass to avoid
  5712. * excessive casting. Package visible for use by subclass.
  5713. * @serial the wrapped list
  5714. */
  5715. final List<E> list;
  5716. /**
  5717. * Wrap a given list.
  5718. * @param l the list to wrap
  5719. * @param type the type of the elements within the checked list.
  5720. * @throws NullPointerException if l is null
  5721. */
  5722. CheckedList(List<E> l, Class<E> type)
  5723. {
  5724. super(l, type);
  5725. list = l;
  5726. }
  5727. /**
  5728. * Adds the supplied element to the underlying list at the specified
  5729. * index, provided it is of the right type.
  5730. *
  5731. * @param index The index at which to place the new element.
  5732. * @param o the object to add.
  5733. * @throws ClassCastException if the type of the object is not a
  5734. * valid type for the underlying collection.
  5735. */
  5736. public void add(int index, E o)
  5737. {
  5738. if (type.isInstance(o))
  5739. list.add(index, o);
  5740. else
  5741. throw new ClassCastException("The object is of the wrong type.");
  5742. }
  5743. /**
  5744. * Adds the members of the supplied collection to the underlying
  5745. * collection at the specified index, provided they are all of the
  5746. * correct type.
  5747. *
  5748. * @param index the index at which to place the new element.
  5749. * @param coll the collections of objects to add.
  5750. * @throws ClassCastException if the type of any element in c is not a
  5751. * valid type for the underlying collection.
  5752. */
  5753. public boolean addAll(int index, Collection<? extends E> coll)
  5754. {
  5755. Collection<E> typedColl = (Collection<E>) coll;
  5756. final Iterator<E> it = typedColl.iterator();
  5757. while (it.hasNext())
  5758. {
  5759. if (!type.isInstance(it.next()))
  5760. throw new ClassCastException("A member of the collection is not of the correct type.");
  5761. }
  5762. return list.addAll(index, coll);
  5763. }
  5764. /**
  5765. * Returns <code>true</code> if the object, o, is an instance of
  5766. * <code>List</code> with the same size and elements
  5767. * as the underlying list.
  5768. *
  5769. * @param o The object to compare.
  5770. * @return <code>true</code> if o is equivalent to the underlying list.
  5771. */
  5772. public boolean equals(Object o)
  5773. {
  5774. return list.equals(o);
  5775. }
  5776. /**
  5777. * Retrieves the element at a given index in the underlying list.
  5778. *
  5779. * @param index the index of the element to be returned
  5780. * @return the element at the specified index in the underlying list
  5781. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  5782. */
  5783. public E get(int index)
  5784. {
  5785. return list.get(index);
  5786. }
  5787. /**
  5788. * Computes the hash code for the underlying list.
  5789. * The exact computation is described in the documentation
  5790. * of the <code>List</code> interface.
  5791. *
  5792. * @return The hash code of the underlying list.
  5793. * @see List#hashCode()
  5794. */
  5795. public int hashCode()
  5796. {
  5797. return list.hashCode();
  5798. }
  5799. /**
  5800. * Obtain the first index at which a given object is to be found in the
  5801. * underlying list.
  5802. *
  5803. * @param o the object to search for
  5804. * @return the least integer n such that <code>o == null ? get(n) == null :
  5805. * o.equals(get(n))</code>, or -1 if there is no such index.
  5806. * @throws ClassCastException if the type of o is not a valid
  5807. * type for the underlying list.
  5808. * @throws NullPointerException if o is null and the underlying
  5809. * list does not support null values.
  5810. */
  5811. public int indexOf(Object o)
  5812. {
  5813. return list.indexOf(o);
  5814. }
  5815. /**
  5816. * Obtain the last index at which a given object is to be found in the
  5817. * underlying list.
  5818. *
  5819. * @return the greatest integer n such that
  5820. * <code>o == null ? get(n) == null : o.equals(get(n))</code>,
  5821. * or -1 if there is no such index.
  5822. * @throws ClassCastException if the type of o is not a valid
  5823. * type for the underlying list.
  5824. * @throws NullPointerException if o is null and the underlying
  5825. * list does not support null values.
  5826. */
  5827. public int lastIndexOf(Object o)
  5828. {
  5829. return list.lastIndexOf(o);
  5830. }
  5831. /**
  5832. * Obtains a list iterator over the underlying list, starting at the
  5833. * beginning and maintaining the checked nature of this list.
  5834. *
  5835. * @return a <code>CheckedListIterator</code> over the elements of the
  5836. * underlying list, in order, starting at the beginning.
  5837. */
  5838. public ListIterator<E> listIterator()
  5839. {
  5840. return new CheckedListIterator<E>(list.listIterator(), type);
  5841. }
  5842. /**
  5843. * Obtains a list iterator over the underlying list, starting at the
  5844. * specified index and maintaining the checked nature of this list. An
  5845. * initial call to <code>next()</code> will retrieve the element at the
  5846. * specified index, and an initial call to <code>previous()</code> will
  5847. * retrieve the element at index - 1.
  5848. *
  5849. * @param index the position, between 0 and size() inclusive, to begin the
  5850. * iteration from.
  5851. * @return a <code>CheckedListIterator</code> over the elements of the
  5852. * underlying list, in order, starting at the specified index.
  5853. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  5854. */
  5855. public ListIterator<E> listIterator(int index)
  5856. {
  5857. return new CheckedListIterator<E>(list.listIterator(index), type);
  5858. }
  5859. /**
  5860. * Removes the element at the specified index.
  5861. *
  5862. * @param index The index of the element to remove.
  5863. * @return the removed element.
  5864. */
  5865. public E remove(int index)
  5866. {
  5867. return list.remove(index);
  5868. }
  5869. /**
  5870. * Replaces the element at the specified index in the underlying list
  5871. * with that supplied.
  5872. *
  5873. * @param index the index of the element to replace.
  5874. * @param o the new object to place at the specified index.
  5875. * @return the replaced element.
  5876. */
  5877. public E set(int index, E o)
  5878. {
  5879. return list.set(index, o);
  5880. }
  5881. /**
  5882. * Obtain a List view of a subsection of the underlying list, from
  5883. * fromIndex (inclusive) to toIndex (exclusive). If the two indices
  5884. * are equal, the sublist is empty. The returned list will be
  5885. * checked, like this list. Changes to the elements of the
  5886. * returned list will be reflected in the underlying list. The effect
  5887. * of structural modifications is undefined.
  5888. *
  5889. * @param fromIndex the index that the returned list should start from
  5890. * (inclusive).
  5891. * @param toIndex the index that the returned list should go
  5892. * to (exclusive).
  5893. * @return a List backed by a subsection of the underlying list.
  5894. * @throws IndexOutOfBoundsException if fromIndex &lt; 0
  5895. * || toIndex &gt; size() || fromIndex &gt; toIndex.
  5896. */
  5897. public List<E> subList(int fromIndex, int toIndex)
  5898. {
  5899. return checkedList(list.subList(fromIndex, toIndex), type);
  5900. }
  5901. } // class CheckedList
  5902. /**
  5903. * The implementation of {@link #checkedList(List)} for random-access
  5904. * lists. This class name is required for compatibility with Sun's JDK
  5905. * serializability.
  5906. *
  5907. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  5908. * @since 1.5
  5909. */
  5910. private static final class CheckedRandomAccessList<E>
  5911. extends CheckedList<E>
  5912. implements RandomAccess
  5913. {
  5914. /**
  5915. * Compatible with JDK 1.5.
  5916. */
  5917. private static final long serialVersionUID = 1638200125423088369L;
  5918. /**
  5919. * Wrap a given list.
  5920. * @param l the list to wrap
  5921. * @param type the type of the elements within the checked list.
  5922. * @throws NullPointerException if l is null
  5923. */
  5924. CheckedRandomAccessList(List<E> l, Class<E> type)
  5925. {
  5926. super(l, type);
  5927. }
  5928. } // class CheckedRandomAccessList
  5929. /**
  5930. * The implementation of {@link CheckedList#listIterator()}.
  5931. *
  5932. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  5933. * @since 1.5
  5934. */
  5935. private static final class CheckedListIterator<E>
  5936. extends CheckedIterator<E>
  5937. implements ListIterator<E>
  5938. {
  5939. /**
  5940. * The wrapped iterator, stored both here and in the superclass to
  5941. * avoid excessive casting.
  5942. */
  5943. private final ListIterator<E> li;
  5944. /**
  5945. * Only trusted code creates a wrapper.
  5946. * @param li the wrapped iterator
  5947. */
  5948. CheckedListIterator(ListIterator<E> li, Class<E> type)
  5949. {
  5950. super(li, type);
  5951. this.li = li;
  5952. }
  5953. /**
  5954. * Adds the supplied object at the current iterator position, provided
  5955. * it is of the correct type.
  5956. *
  5957. * @param o the object to add.
  5958. * @throws ClassCastException if the type of the object is not a
  5959. * valid type for the underlying collection.
  5960. */
  5961. public void add(E o)
  5962. {
  5963. if (type.isInstance(o))
  5964. li.add(o);
  5965. else
  5966. throw new ClassCastException("The object is of the wrong type.");
  5967. }
  5968. /**
  5969. * Tests whether there are still elements to be retrieved from the
  5970. * underlying collection by <code>previous()</code>. When this method
  5971. * returns <code>true</code>, an exception will not be thrown on calling
  5972. * <code>previous()</code>.
  5973. *
  5974. * @return <code>true</code> if there is at least one more element prior
  5975. * to the current position in the underlying list.
  5976. */
  5977. public boolean hasPrevious()
  5978. {
  5979. return li.hasPrevious();
  5980. }
  5981. /**
  5982. * Find the index of the element that would be returned by a call to next.
  5983. * If <code>hasNext()</code> returns <code>false</code>, this returns the
  5984. * list size.
  5985. *
  5986. * @return the index of the element that would be returned by
  5987. * <code>next()</code>.
  5988. */
  5989. public int nextIndex()
  5990. {
  5991. return li.nextIndex();
  5992. }
  5993. /**
  5994. * Obtains the previous element in the underlying list.
  5995. *
  5996. * @return the previous element in the list.
  5997. * @throws NoSuchElementException if there are no more prior elements.
  5998. */
  5999. public E previous()
  6000. {
  6001. return li.previous();
  6002. }
  6003. /**
  6004. * Find the index of the element that would be returned by a call to
  6005. * previous. If <code>hasPrevious()</code> returns <code>false</code>,
  6006. * this returns -1.
  6007. *
  6008. * @return the index of the element that would be returned by
  6009. * <code>previous()</code>.
  6010. */
  6011. public int previousIndex()
  6012. {
  6013. return li.previousIndex();
  6014. }
  6015. /**
  6016. * Sets the next element to that supplied, provided that it is of the
  6017. * correct type.
  6018. *
  6019. * @param o The new object to replace the existing one.
  6020. * @throws ClassCastException if the type of the object is not a
  6021. * valid type for the underlying collection.
  6022. */
  6023. public void set(E o)
  6024. {
  6025. if (type.isInstance(o))
  6026. li.set(o);
  6027. else
  6028. throw new ClassCastException("The object is of the wrong type.");
  6029. }
  6030. } // class CheckedListIterator
  6031. /**
  6032. * <p>
  6033. * Returns a dynamically typesafe view of the given map,
  6034. * where any modification is first checked to ensure that the type
  6035. * of the new data is appropriate. Although the addition of
  6036. * generics and parametrically-typed collections prevents an
  6037. * incorrect type of element being added to a collection at
  6038. * compile-time, via static type checking, this can be overridden by
  6039. * casting. In contrast, wrapping the collection within a
  6040. * dynamically-typesafe wrapper, using this and associated methods,
  6041. * <emph>guarantees</emph> that the collection will only contain
  6042. * elements of an appropriate type (provided it only contains such
  6043. * at the type of wrapping, and all subsequent access is via the
  6044. * wrapper). This can be useful for debugging the cause of a
  6045. * <code>ClassCastException</code> caused by erroneous casting, or
  6046. * for protecting collections from corruption by external libraries.
  6047. * </p>
  6048. * <p>
  6049. * The returned Map implements Serializable, but can only be serialized if
  6050. * the map it wraps is likewise Serializable.
  6051. * </p>
  6052. *
  6053. * @param m the map to wrap
  6054. * @param keyType the dynamic type of the map's keys.
  6055. * @param valueType the dynamic type of the map's values.
  6056. * @return a dynamically typesafe view of the map
  6057. * @see Serializable
  6058. */
  6059. public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType,
  6060. Class<V> valueType)
  6061. {
  6062. return new CheckedMap<K, V>(m, keyType, valueType);
  6063. }
  6064. /**
  6065. * The implementation of {@link #checkedMap(Map)}. This
  6066. * class name is required for compatibility with Sun's JDK serializability.
  6067. *
  6068. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6069. * @since 1.5
  6070. */
  6071. private static class CheckedMap<K, V>
  6072. implements Map<K, V>, Serializable
  6073. {
  6074. /**
  6075. * Compatible with JDK 1.5.
  6076. */
  6077. private static final long serialVersionUID = 5742860141034234728L;
  6078. /**
  6079. * The wrapped map.
  6080. * @serial the real map
  6081. */
  6082. private final Map<K, V> m;
  6083. /**
  6084. * The type of the map's keys.
  6085. * @serial the key type.
  6086. */
  6087. final Class<K> keyType;
  6088. /**
  6089. * The type of the map's values.
  6090. * @serial the value type.
  6091. */
  6092. final Class<V> valueType;
  6093. /**
  6094. * Cache the entry set.
  6095. */
  6096. private transient Set<Map.Entry<K, V>> entries;
  6097. /**
  6098. * Cache the key set.
  6099. */
  6100. private transient Set<K> keys;
  6101. /**
  6102. * Cache the value collection.
  6103. */
  6104. private transient Collection<V> values;
  6105. /**
  6106. * Wrap a given map.
  6107. * @param m the map to wrap
  6108. * @param keyType the dynamic type of the map's keys.
  6109. * @param valueType the dynamic type of the map's values.
  6110. * @throws NullPointerException if m is null
  6111. */
  6112. CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType)
  6113. {
  6114. this.m = m;
  6115. this.keyType = keyType;
  6116. this.valueType = valueType;
  6117. if (m == null)
  6118. throw new NullPointerException();
  6119. }
  6120. /**
  6121. * Clears all pairs from the map.
  6122. */
  6123. public void clear()
  6124. {
  6125. m.clear();
  6126. }
  6127. /**
  6128. * Returns <code>true</code> if the underlying map contains a mapping for
  6129. * the given key.
  6130. *
  6131. * @param key the key to search for
  6132. * @return <code>true</code> if the map contains the key
  6133. * @throws ClassCastException if the key is of an inappropriate type
  6134. * @throws NullPointerException if key is <code>null</code> but the map
  6135. * does not permit null keys
  6136. */
  6137. public boolean containsKey(Object key)
  6138. {
  6139. return m.containsKey(key);
  6140. }
  6141. /**
  6142. * Returns <code>true</code> if the underlying map contains at least one
  6143. * mapping with the given value. In other words, it returns
  6144. * <code>true</code> if a value v exists where
  6145. * <code>(value == null ? v == null : value.equals(v))</code>.
  6146. * This usually requires linear time.
  6147. *
  6148. * @param value the value to search for
  6149. * @return <code>true</code> if the map contains the value
  6150. * @throws ClassCastException if the type of the value is not a valid type
  6151. * for this map.
  6152. * @throws NullPointerException if the value is null and the map doesn't
  6153. * support null values.
  6154. */
  6155. public boolean containsValue(Object value)
  6156. {
  6157. return m.containsValue(value);
  6158. }
  6159. /**
  6160. * <p>
  6161. * Returns a checked set view of the entries in the underlying map.
  6162. * Each element in the set is a unmodifiable variant of
  6163. * <code>Map.Entry</code>.
  6164. * </p>
  6165. * <p>
  6166. * The set is backed by the map, so that changes in one show up in the
  6167. * other. Modifications made while an iterator is in progress cause
  6168. * undefined behavior.
  6169. * </p>
  6170. *
  6171. * @return the checked set view of all mapping entries.
  6172. * @see Map.Entry
  6173. */
  6174. public Set<Map.Entry<K, V>> entrySet()
  6175. {
  6176. if (entries == null)
  6177. {
  6178. Class<Map.Entry<K,V>> klass =
  6179. (Class<Map.Entry<K,V>>) (Class) Map.Entry.class;
  6180. entries = new CheckedEntrySet<Map.Entry<K,V>,K,V>(m.entrySet(),
  6181. klass,
  6182. keyType,
  6183. valueType);
  6184. }
  6185. return entries;
  6186. }
  6187. /**
  6188. * The implementation of {@link CheckedMap#entrySet()}. This class
  6189. * is <emph>not</emph> serializable.
  6190. *
  6191. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6192. * @since 1.5
  6193. */
  6194. private static final class CheckedEntrySet<E,SK,SV>
  6195. extends CheckedSet<E>
  6196. {
  6197. /**
  6198. * The type of the map's keys.
  6199. * @serial the key type.
  6200. */
  6201. private final Class<SK> keyType;
  6202. /**
  6203. * The type of the map's values.
  6204. * @serial the value type.
  6205. */
  6206. private final Class<SV> valueType;
  6207. /**
  6208. * Wrap a given set of map entries.
  6209. *
  6210. * @param s the set to wrap.
  6211. * @param type the type of the set's entries.
  6212. * @param keyType the type of the map's keys.
  6213. * @param valueType the type of the map's values.
  6214. */
  6215. CheckedEntrySet(Set<E> s, Class<E> type, Class<SK> keyType,
  6216. Class<SV> valueType)
  6217. {
  6218. super(s, type);
  6219. this.keyType = keyType;
  6220. this.valueType = valueType;
  6221. }
  6222. // The iterator must return checked map entries.
  6223. public Iterator<E> iterator()
  6224. {
  6225. return new CheckedIterator<E>(c.iterator(), type)
  6226. {
  6227. /**
  6228. * Obtains the next element from the underlying set of
  6229. * map entries.
  6230. *
  6231. * @return the next element in the collection.
  6232. * @throws NoSuchElementException if there are no more elements.
  6233. */
  6234. public E next()
  6235. {
  6236. final Map.Entry e = (Map.Entry) super.next();
  6237. return (E) new Map.Entry()
  6238. {
  6239. /**
  6240. * Returns <code>true</code> if the object, o, is also a map
  6241. * entry with an identical key and value.
  6242. *
  6243. * @param o the object to compare.
  6244. * @return <code>true</code> if o is an equivalent map entry.
  6245. */
  6246. public boolean equals(Object o)
  6247. {
  6248. return e.equals(o);
  6249. }
  6250. /**
  6251. * Returns the key of this map entry.
  6252. *
  6253. * @return the key.
  6254. */
  6255. public Object getKey()
  6256. {
  6257. return e.getKey();
  6258. }
  6259. /**
  6260. * Returns the value of this map entry.
  6261. *
  6262. * @return the value.
  6263. */
  6264. public Object getValue()
  6265. {
  6266. return e.getValue();
  6267. }
  6268. /**
  6269. * Computes the hash code of this map entry.
  6270. * The computation is described in the <code>Map</code>
  6271. * interface documentation.
  6272. *
  6273. * @return the hash code of this entry.
  6274. * @see Map#hashCode()
  6275. */
  6276. public int hashCode()
  6277. {
  6278. return e.hashCode();
  6279. }
  6280. /**
  6281. * Sets the value of this map entry, provided it is of the
  6282. * right type.
  6283. *
  6284. * @param value The new value.
  6285. * @throws ClassCastException if the type of the value is not
  6286. * a valid type for the underlying
  6287. * map.
  6288. */
  6289. public Object setValue(Object value)
  6290. {
  6291. if (valueType.isInstance(value))
  6292. return e.setValue(value);
  6293. else
  6294. throw new ClassCastException("The value is of the wrong type.");
  6295. }
  6296. /**
  6297. * Returns a textual representation of the map entry.
  6298. *
  6299. * @return The map entry as a <code>String</code>.
  6300. */
  6301. public String toString()
  6302. {
  6303. return e.toString();
  6304. }
  6305. };
  6306. }
  6307. };
  6308. }
  6309. } // class CheckedEntrySet
  6310. /**
  6311. * Returns <code>true</code> if the object, o, is also an instance
  6312. * of <code>Map</code> with an equal set of map entries.
  6313. *
  6314. * @param o The object to compare.
  6315. * @return <code>true</code> if o is an equivalent map.
  6316. */
  6317. public boolean equals(Object o)
  6318. {
  6319. return m.equals(o);
  6320. }
  6321. /**
  6322. * Returns the value associated with the supplied key or
  6323. * null if no such mapping exists. An ambiguity can occur
  6324. * if null values are accepted by the underlying map.
  6325. * In this case, <code>containsKey()</code> can be used
  6326. * to separate the two possible cases of a null result.
  6327. *
  6328. * @param key The key to look up.
  6329. * @return the value associated with the key, or null if key not in map.
  6330. * @throws ClassCastException if the key is an inappropriate type.
  6331. * @throws NullPointerException if this map does not accept null keys.
  6332. * @see #containsKey(Object)
  6333. */
  6334. public V get(Object key)
  6335. {
  6336. return m.get(key);
  6337. }
  6338. /**
  6339. * Adds a new pair to the map, provided both the key and the value are
  6340. * of the correct types.
  6341. *
  6342. * @param key The new key.
  6343. * @param value The new value.
  6344. * @return the previous value of the key, or null if there was no mapping.
  6345. * @throws ClassCastException if the type of the key or the value is
  6346. * not a valid type for the underlying map.
  6347. */
  6348. public V put(K key, V value)
  6349. {
  6350. if (keyType.isInstance(key))
  6351. {
  6352. if (valueType.isInstance(value))
  6353. return m.put(key,value);
  6354. else
  6355. throw new ClassCastException("The value is of the wrong type.");
  6356. }
  6357. throw new ClassCastException("The key is of the wrong type.");
  6358. }
  6359. /**
  6360. * Computes the hash code for the underlying map, as the sum
  6361. * of the hash codes of all entries.
  6362. *
  6363. * @return The hash code of the underlying map.
  6364. * @see Map.Entry#hashCode()
  6365. */
  6366. public int hashCode()
  6367. {
  6368. return m.hashCode();
  6369. }
  6370. /**
  6371. * Returns <code>true</code> if the underlying map contains no entries.
  6372. *
  6373. * @return <code>true</code> if the map is empty.
  6374. */
  6375. public boolean isEmpty()
  6376. {
  6377. return m.isEmpty();
  6378. }
  6379. /**
  6380. * <p>
  6381. * Returns a checked set view of the keys in the underlying map.
  6382. * The set is backed by the map, so that changes in one show up in the
  6383. * other.
  6384. * </p>
  6385. * <p>
  6386. * Modifications made while an iterator is in progress cause undefined
  6387. * behavior. These modifications are again limited to the values of
  6388. * the keys.
  6389. * </p>
  6390. *
  6391. * @return the set view of all keys.
  6392. */
  6393. public Set<K> keySet()
  6394. {
  6395. if (keys == null)
  6396. keys = new CheckedSet<K>(m.keySet(), keyType);
  6397. return keys;
  6398. }
  6399. /**
  6400. * Adds all pairs within the supplied map to the underlying map,
  6401. * provided they are all have the correct key and value types.
  6402. *
  6403. * @param map the map, the entries of which should be added
  6404. * to the underlying map.
  6405. * @throws ClassCastException if the type of a key or value is
  6406. * not a valid type for the underlying map.
  6407. */
  6408. public void putAll(Map<? extends K, ? extends V> map)
  6409. {
  6410. Map<K,V> typedMap = (Map<K,V>) map;
  6411. final Iterator<Map.Entry<K,V>> it = typedMap.entrySet().iterator();
  6412. while (it.hasNext())
  6413. {
  6414. final Map.Entry<K,V> entry = it.next();
  6415. if (!keyType.isInstance(entry.getKey()))
  6416. throw new ClassCastException("A key is of the wrong type.");
  6417. if (!valueType.isInstance(entry.getValue()))
  6418. throw new ClassCastException("A value is of the wrong type.");
  6419. }
  6420. m.putAll(typedMap);
  6421. }
  6422. /**
  6423. * Removes a pair from the map.
  6424. *
  6425. * @param o The key of the entry to remove.
  6426. * @return The value the key was associated with, or null
  6427. * if no such mapping existed. Null is also returned
  6428. * if the removed entry had a null key.
  6429. * @throws UnsupportedOperationException as an unmodifiable
  6430. * map does not support the <code>remove</code> operation.
  6431. */
  6432. public V remove(Object o)
  6433. {
  6434. return m.remove(o);
  6435. }
  6436. /**
  6437. * Returns the number of key-value mappings in the underlying map.
  6438. * If there are more than Integer.MAX_VALUE mappings, Integer.MAX_VALUE
  6439. * is returned.
  6440. *
  6441. * @return the number of mappings.
  6442. */
  6443. public int size()
  6444. {
  6445. return m.size();
  6446. }
  6447. /**
  6448. * Returns a textual representation of the map.
  6449. *
  6450. * @return The map in the form of a <code>String</code>.
  6451. */
  6452. public String toString()
  6453. {
  6454. return m.toString();
  6455. }
  6456. /**
  6457. * <p>
  6458. * Returns a unmodifiable collection view of the values in the underlying
  6459. * map. The collection is backed by the map, so that changes in one show
  6460. * up in the other.
  6461. * </p>
  6462. * <p>
  6463. * Modifications made while an iterator is in progress cause undefined
  6464. * behavior. These modifications are again limited to the values of
  6465. * the keys.
  6466. * </p>
  6467. *
  6468. * @return the collection view of all values.
  6469. */
  6470. public Collection<V> values()
  6471. {
  6472. if (values == null)
  6473. values = new CheckedCollection<V>(m.values(), valueType);
  6474. return values;
  6475. }
  6476. } // class CheckedMap
  6477. /**
  6478. * <p>
  6479. * Returns a dynamically typesafe view of the given set,
  6480. * where any modification is first checked to ensure that the type
  6481. * of the new data is appropriate. Although the addition of
  6482. * generics and parametrically-typed collections prevents an
  6483. * incorrect type of element being added to a collection at
  6484. * compile-time, via static type checking, this can be overridden by
  6485. * casting. In contrast, wrapping the collection within a
  6486. * dynamically-typesafe wrapper, using this and associated methods,
  6487. * <emph>guarantees</emph> that the collection will only contain
  6488. * elements of an appropriate type (provided it only contains such
  6489. * at the type of wrapping, and all subsequent access is via the
  6490. * wrapper). This can be useful for debugging the cause of a
  6491. * <code>ClassCastException</code> caused by erroneous casting, or
  6492. * for protecting collections from corruption by external libraries.
  6493. * </p>
  6494. * <p>
  6495. * The returned Set implements Serializable, but can only be serialized if
  6496. * the set it wraps is likewise Serializable.
  6497. * </p>
  6498. *
  6499. * @param s the set to wrap.
  6500. * @param type the type of the elements within the checked list.
  6501. * @return a dynamically typesafe view of the set
  6502. * @see Serializable
  6503. */
  6504. public static <E> Set<E> checkedSet(Set<E> s, Class<E> type)
  6505. {
  6506. return new CheckedSet<E>(s, type);
  6507. }
  6508. /**
  6509. * The implementation of {@link #checkedSet(Set)}. This class
  6510. * name is required for compatibility with Sun's JDK serializability.
  6511. *
  6512. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6513. * @since 1.5
  6514. */
  6515. private static class CheckedSet<E>
  6516. extends CheckedCollection<E>
  6517. implements Set<E>
  6518. {
  6519. /**
  6520. * Compatible with JDK 1.5.
  6521. */
  6522. private static final long serialVersionUID = 4694047833775013803L;
  6523. /**
  6524. * Wrap a given set.
  6525. *
  6526. * @param s the set to wrap
  6527. * @throws NullPointerException if s is null
  6528. */
  6529. CheckedSet(Set<E> s, Class<E> type)
  6530. {
  6531. super(s, type);
  6532. }
  6533. /**
  6534. * Returns <code>true</code> if the object, o, is also an instance of
  6535. * <code>Set</code> of the same size and with the same entries.
  6536. *
  6537. * @return <code>true</code> if o is an equivalent set.
  6538. */
  6539. public boolean equals(Object o)
  6540. {
  6541. return c.equals(o);
  6542. }
  6543. /**
  6544. * Computes the hash code of this set, as the sum of the
  6545. * hash codes of all elements within the set.
  6546. *
  6547. * @return the hash code of the set.
  6548. */
  6549. public int hashCode()
  6550. {
  6551. return c.hashCode();
  6552. }
  6553. } // class CheckedSet
  6554. /**
  6555. * <p>
  6556. * Returns a dynamically typesafe view of the given sorted map,
  6557. * where any modification is first checked to ensure that the type
  6558. * of the new data is appropriate. Although the addition of
  6559. * generics and parametrically-typed collections prevents an
  6560. * incorrect type of element being added to a collection at
  6561. * compile-time, via static type checking, this can be overridden by
  6562. * casting. In contrast, wrapping the collection within a
  6563. * dynamically-typesafe wrapper, using this and associated methods,
  6564. * <emph>guarantees</emph> that the collection will only contain
  6565. * elements of an appropriate type (provided it only contains such
  6566. * at the type of wrapping, and all subsequent access is via the
  6567. * wrapper). This can be useful for debugging the cause of a
  6568. * <code>ClassCastException</code> caused by erroneous casting, or
  6569. * for protecting collections from corruption by external libraries.
  6570. * </p>
  6571. * <p>
  6572. * The returned SortedMap implements Serializable, but can only be
  6573. * serialized if the map it wraps is likewise Serializable.
  6574. * </p>
  6575. *
  6576. * @param m the map to wrap.
  6577. * @param keyType the dynamic type of the map's keys.
  6578. * @param valueType the dynamic type of the map's values.
  6579. * @return a dynamically typesafe view of the map
  6580. * @see Serializable
  6581. */
  6582. public static <K, V> SortedMap<K, V> checkedSortedMap(SortedMap<K, V> m,
  6583. Class<K> keyType,
  6584. Class<V> valueType)
  6585. {
  6586. return new CheckedSortedMap<K, V>(m, keyType, valueType);
  6587. }
  6588. /**
  6589. * The implementation of {@link #checkedSortedMap(SortedMap,Class,Class)}.
  6590. * This class name is required for compatibility with Sun's JDK
  6591. * serializability.
  6592. *
  6593. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6594. */
  6595. private static class CheckedSortedMap<K, V>
  6596. extends CheckedMap<K, V>
  6597. implements SortedMap<K, V>
  6598. {
  6599. /**
  6600. * Compatible with JDK 1.5.
  6601. */
  6602. private static final long serialVersionUID = 1599671320688067438L;
  6603. /**
  6604. * The wrapped map; stored both here and in the superclass to avoid
  6605. * excessive casting.
  6606. * @serial the wrapped map
  6607. */
  6608. private final SortedMap<K, V> sm;
  6609. /**
  6610. * Wrap a given map.
  6611. *
  6612. * @param sm the map to wrap
  6613. * @param keyType the dynamic type of the map's keys.
  6614. * @param valueType the dynamic type of the map's values.
  6615. * @throws NullPointerException if sm is null
  6616. */
  6617. CheckedSortedMap(SortedMap<K, V> sm, Class<K> keyType, Class<V> valueType)
  6618. {
  6619. super(sm, keyType, valueType);
  6620. this.sm = sm;
  6621. }
  6622. /**
  6623. * Returns the comparator used in sorting the underlying map,
  6624. * or null if it is the keys' natural ordering.
  6625. *
  6626. * @return the sorting comparator.
  6627. */
  6628. public Comparator<? super K> comparator()
  6629. {
  6630. return sm.comparator();
  6631. }
  6632. /**
  6633. * Returns the first (lowest sorted) key in the map.
  6634. *
  6635. * @return the first key.
  6636. * @throws NoSuchElementException if this map is empty.
  6637. */
  6638. public K firstKey()
  6639. {
  6640. return sm.firstKey();
  6641. }
  6642. /**
  6643. * <p>
  6644. * Returns a checked view of the portion of the map strictly less
  6645. * than toKey. The view is backed by the underlying map, so changes in
  6646. * one show up in the other. The submap supports all optional operations
  6647. * of the original. This operation is equivalent to
  6648. * <code>subMap(firstKey(), toKey)</code>.
  6649. * </p>
  6650. * <p>
  6651. * The returned map throws an IllegalArgumentException any time a key is
  6652. * used which is out of the range of toKey. Note that the endpoint, toKey,
  6653. * is not included; if you want this value to be included, pass its
  6654. * successor object in to toKey. For example, for Integers, you could
  6655. * request <code>headMap(new Integer(limit.intValue() + 1))</code>.
  6656. * </p>
  6657. *
  6658. * @param toKey the exclusive upper range of the submap.
  6659. * @return the submap.
  6660. * @throws ClassCastException if toKey is not comparable to the map
  6661. * contents.
  6662. * @throws IllegalArgumentException if this is a subMap, and toKey is out
  6663. * of range.
  6664. * @throws NullPointerException if toKey is null but the map does not allow
  6665. * null keys.
  6666. */
  6667. public SortedMap<K, V> headMap(K toKey)
  6668. {
  6669. return new CheckedSortedMap<K, V>(sm.headMap(toKey), keyType, valueType);
  6670. }
  6671. /**
  6672. * Returns the last (highest sorted) key in the map.
  6673. *
  6674. * @return the last key.
  6675. * @throws NoSuchElementException if this map is empty.
  6676. */
  6677. public K lastKey()
  6678. {
  6679. return sm.lastKey();
  6680. }
  6681. /**
  6682. * <p>
  6683. * Returns a checked view of the portion of the map greater than or
  6684. * equal to fromKey, and strictly less than toKey. The view is backed by
  6685. * the underlying map, so changes in one show up in the other. The submap
  6686. * supports all optional operations of the original.
  6687. * </p>
  6688. * <p>
  6689. * The returned map throws an IllegalArgumentException any time a key is
  6690. * used which is out of the range of fromKey and toKey. Note that the
  6691. * lower endpoint is included, but the upper is not; if you want to
  6692. * change the inclusion or exclusion of an endpoint, pass its successor
  6693. * object in instead. For example, for Integers, you could request
  6694. * <code>subMap(new Integer(lowlimit.intValue() + 1),
  6695. * new Integer(highlimit.intValue() + 1))</code> to reverse
  6696. * the inclusiveness of both endpoints.
  6697. * </p>
  6698. *
  6699. * @param fromKey the inclusive lower range of the submap.
  6700. * @param toKey the exclusive upper range of the submap.
  6701. * @return the submap.
  6702. * @throws ClassCastException if fromKey or toKey is not comparable to
  6703. * the map contents.
  6704. * @throws IllegalArgumentException if this is a subMap, and fromKey or
  6705. * toKey is out of range.
  6706. * @throws NullPointerException if fromKey or toKey is null but the map
  6707. * does not allow null keys.
  6708. */
  6709. public SortedMap<K, V> subMap(K fromKey, K toKey)
  6710. {
  6711. return new CheckedSortedMap<K, V>(sm.subMap(fromKey, toKey), keyType,
  6712. valueType);
  6713. }
  6714. /**
  6715. * <p>
  6716. * Returns a checked view of the portion of the map greater than or
  6717. * equal to fromKey. The view is backed by the underlying map, so changes
  6718. * in one show up in the other. The submap supports all optional operations
  6719. * of the original.
  6720. * </p>
  6721. * <p>
  6722. * The returned map throws an IllegalArgumentException any time a key is
  6723. * used which is out of the range of fromKey. Note that the endpoint,
  6724. * fromKey, is included; if you do not want this value to be included,
  6725. * pass its successor object in to fromKey. For example, for Integers,
  6726. * you could request
  6727. * <code>tailMap(new Integer(limit.intValue() + 1))</code>.
  6728. * </p>
  6729. *
  6730. * @param fromKey the inclusive lower range of the submap
  6731. * @return the submap
  6732. * @throws ClassCastException if fromKey is not comparable to the map
  6733. * contents
  6734. * @throws IllegalArgumentException if this is a subMap, and fromKey is out
  6735. * of range
  6736. * @throws NullPointerException if fromKey is null but the map does not
  6737. * allow null keys
  6738. */
  6739. public SortedMap<K, V> tailMap(K fromKey)
  6740. {
  6741. return new CheckedSortedMap<K, V>(sm.tailMap(fromKey), keyType,
  6742. valueType);
  6743. }
  6744. } // class CheckedSortedMap
  6745. /**
  6746. * <p>
  6747. * Returns a dynamically typesafe view of the given sorted set,
  6748. * where any modification is first checked to ensure that the type
  6749. * of the new data is appropriate. Although the addition of
  6750. * generics and parametrically-typed collections prevents an
  6751. * incorrect type of element being added to a collection at
  6752. * compile-time, via static type checking, this can be overridden by
  6753. * casting. In contrast, wrapping the collection within a
  6754. * dynamically-typesafe wrapper, using this and associated methods,
  6755. * <emph>guarantees</emph> that the collection will only contain
  6756. * elements of an appropriate type (provided it only contains such
  6757. * at the type of wrapping, and all subsequent access is via the
  6758. * wrapper). This can be useful for debugging the cause of a
  6759. * <code>ClassCastException</code> caused by erroneous casting, or
  6760. * for protecting collections from corruption by external libraries.
  6761. * </p>
  6762. * <p>
  6763. * The returned SortedSet implements Serializable, but can only be
  6764. * serialized if the set it wraps is likewise Serializable.
  6765. * </p>
  6766. *
  6767. * @param s the set to wrap.
  6768. * @param type the type of the set's elements.
  6769. * @return a dynamically typesafe view of the set
  6770. * @see Serializable
  6771. */
  6772. public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
  6773. Class<E> type)
  6774. {
  6775. return new CheckedSortedSet<E>(s, type);
  6776. }
  6777. /**
  6778. * The implementation of {@link #checkedSortedSet(SortedSet,Class)}. This
  6779. * class name is required for compatibility with Sun's JDK serializability.
  6780. *
  6781. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6782. * @since 1.5
  6783. */
  6784. private static class CheckedSortedSet<E>
  6785. extends CheckedSet<E>
  6786. implements SortedSet<E>
  6787. {
  6788. /**
  6789. * Compatible with JDK 1.4.
  6790. */
  6791. private static final long serialVersionUID = 1599911165492914959L;
  6792. /**
  6793. * The wrapped set; stored both here and in the superclass to avoid
  6794. * excessive casting.
  6795. *
  6796. * @serial the wrapped set
  6797. */
  6798. private SortedSet<E> ss;
  6799. /**
  6800. * Wrap a given set.
  6801. *
  6802. * @param ss the set to wrap.
  6803. * @param type the type of the set's elements.
  6804. * @throws NullPointerException if ss is null
  6805. */
  6806. CheckedSortedSet(SortedSet<E> ss, Class<E> type)
  6807. {
  6808. super(ss, type);
  6809. this.ss = ss;
  6810. }
  6811. /**
  6812. * Returns the comparator used in sorting the underlying set,
  6813. * or null if it is the elements' natural ordering.
  6814. *
  6815. * @return the sorting comparator
  6816. */
  6817. public Comparator<? super E> comparator()
  6818. {
  6819. return ss.comparator();
  6820. }
  6821. /**
  6822. * Returns the first (lowest sorted) element in the underlying
  6823. * set.
  6824. *
  6825. * @return the first element.
  6826. * @throws NoSuchElementException if the set is empty.
  6827. */
  6828. public E first()
  6829. {
  6830. return ss.first();
  6831. }
  6832. /**
  6833. * <p>
  6834. * Returns a checked view of the portion of the set strictly
  6835. * less than toElement. The view is backed by the underlying set,
  6836. * so changes in one show up in the other. The subset supports
  6837. * all optional operations of the original. This operation
  6838. * is equivalent to <code>subSet(first(), toElement)</code>.
  6839. * </p>
  6840. * <p>
  6841. * The returned set throws an IllegalArgumentException any time an
  6842. * element is used which is out of the range of toElement. Note that
  6843. * the endpoint, toElement, is not included; if you want this value
  6844. * included, pass its successor object in to toElement. For example,
  6845. * for Integers, you could request
  6846. * <code>headSet(new Integer(limit.intValue() + 1))</code>.
  6847. * </p>
  6848. *
  6849. * @param toElement the exclusive upper range of the subset
  6850. * @return the subset.
  6851. * @throws ClassCastException if toElement is not comparable to the set
  6852. * contents.
  6853. * @throws IllegalArgumentException if this is a subSet, and toElement is
  6854. * out of range.
  6855. * @throws NullPointerException if toElement is null but the set does not
  6856. * allow null elements.
  6857. */
  6858. public SortedSet<E> headSet(E toElement)
  6859. {
  6860. return new CheckedSortedSet<E>(ss.headSet(toElement), type);
  6861. }
  6862. /**
  6863. * Returns the last (highest sorted) element in the underlying
  6864. * set.
  6865. *
  6866. * @return the last element.
  6867. * @throws NoSuchElementException if the set is empty.
  6868. */
  6869. public E last()
  6870. {
  6871. return ss.last();
  6872. }
  6873. /**
  6874. * <p>
  6875. * Returns a checked view of the portion of the set greater than or
  6876. * equal to fromElement, and strictly less than toElement. The view is
  6877. * backed by the underlying set, so changes in one show up in the other.
  6878. * The subset supports all optional operations of the original.
  6879. * </p>
  6880. * <p>
  6881. * The returned set throws an IllegalArgumentException any time an
  6882. * element is used which is out of the range of fromElement and toElement.
  6883. * Note that the lower endpoint is included, but the upper is not; if you
  6884. * want to change the inclusion or exclusion of an endpoint, pass its
  6885. * successor object in instead. For example, for Integers, you can request
  6886. * <code>subSet(new Integer(lowlimit.intValue() + 1),
  6887. * new Integer(highlimit.intValue() + 1))</code> to reverse
  6888. * the inclusiveness of both endpoints.
  6889. * </p>
  6890. *
  6891. * @param fromElement the inclusive lower range of the subset.
  6892. * @param toElement the exclusive upper range of the subset.
  6893. * @return the subset.
  6894. * @throws ClassCastException if fromElement or toElement is not comparable
  6895. * to the set contents.
  6896. * @throws IllegalArgumentException if this is a subSet, and fromElement or
  6897. * toElement is out of range.
  6898. * @throws NullPointerException if fromElement or toElement is null but the
  6899. * set does not allow null elements.
  6900. */
  6901. public SortedSet<E> subSet(E fromElement, E toElement)
  6902. {
  6903. return new CheckedSortedSet<E>(ss.subSet(fromElement, toElement), type);
  6904. }
  6905. /**
  6906. * <p>
  6907. * Returns a checked view of the portion of the set greater than or equal
  6908. * to fromElement. The view is backed by the underlying set, so changes in
  6909. * one show up in the other. The subset supports all optional operations
  6910. * of the original.
  6911. * </p>
  6912. * <p>
  6913. * The returned set throws an IllegalArgumentException any time an
  6914. * element is used which is out of the range of fromElement. Note that
  6915. * the endpoint, fromElement, is included; if you do not want this value
  6916. * to be included, pass its successor object in to fromElement. For
  6917. * example, for Integers, you could request
  6918. * <code>tailSet(new Integer(limit.intValue() + 1))</code>.
  6919. * </p>
  6920. *
  6921. * @param fromElement the inclusive lower range of the subset
  6922. * @return the subset.
  6923. * @throws ClassCastException if fromElement is not comparable to the set
  6924. * contents.
  6925. * @throws IllegalArgumentException if this is a subSet, and fromElement is
  6926. * out of range.
  6927. * @throws NullPointerException if fromElement is null but the set does not
  6928. * allow null elements.
  6929. */
  6930. public SortedSet<E> tailSet(E fromElement)
  6931. {
  6932. return new CheckedSortedSet<E>(ss.tailSet(fromElement), type);
  6933. }
  6934. } // class CheckedSortedSet
  6935. /**
  6936. * Returns a view of a {@link Deque} as a stack or LIFO (Last-In-First-Out)
  6937. * {@link Queue}. Each call to the LIFO queue corresponds to one
  6938. * equivalent method call to the underlying deque, with the exception
  6939. * of {@link Collection#addAll(Collection)}, which is emulated by a series
  6940. * of {@link Deque#push(E)} calls.
  6941. *
  6942. * @param deque the deque to convert to a LIFO queue.
  6943. * @return a LIFO queue.
  6944. * @since 1.6
  6945. */
  6946. public static <T> Queue<T> asLifoQueue(Deque<T> deque)
  6947. {
  6948. return new LIFOQueue<T>(deque);
  6949. }
  6950. /**
  6951. * Returns a set backed by the supplied map. The resulting set
  6952. * has the same performance, concurrency and ordering characteristics
  6953. * as the original map. The supplied map must be empty and should not
  6954. * be used after the set is created. Each call to the set corresponds
  6955. * to one equivalent method call to the underlying map, with the exception
  6956. * of {@link Set#addAll(Collection)} which is emulated by a series of
  6957. * calls to <code>put</code>.
  6958. *
  6959. * @param map the map to convert to a set.
  6960. * @return a set backed by the supplied map.
  6961. * @throws IllegalArgumentException if the map is not empty.
  6962. * @since 1.6
  6963. */
  6964. public static <E> Set<E> newSetFromMap(Map<E,Boolean> map)
  6965. {
  6966. return new MapSet<E>(map);
  6967. }
  6968. /**
  6969. * The implementation of {@link #asLIFOQueue(Deque)}.
  6970. *
  6971. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  6972. * @since 1.6
  6973. */
  6974. private static class LIFOQueue<T>
  6975. extends AbstractQueue<T>
  6976. {
  6977. /**
  6978. * The backing deque.
  6979. */
  6980. private Deque<T> deque;
  6981. /**
  6982. * Constructs a new {@link LIFOQueue} with the specified
  6983. * backing {@link Deque}.
  6984. *
  6985. * @param deque the backing deque.
  6986. */
  6987. public LIFOQueue(Deque<T> deque)
  6988. {
  6989. this.deque = deque;
  6990. }
  6991. public boolean add(T e)
  6992. {
  6993. return deque.offerFirst(e);
  6994. }
  6995. public boolean addAll(Collection<? extends T> c)
  6996. {
  6997. boolean result = false;
  6998. final Iterator<? extends T> it = c.iterator();
  6999. while (it.hasNext())
  7000. result |= deque.offerFirst(it.next());
  7001. return result;
  7002. }
  7003. public void clear()
  7004. {
  7005. deque.clear();
  7006. }
  7007. public boolean isEmpty()
  7008. {
  7009. return deque.isEmpty();
  7010. }
  7011. public Iterator<T> iterator()
  7012. {
  7013. return deque.iterator();
  7014. }
  7015. public boolean offer(T e)
  7016. {
  7017. return deque.offerFirst(e);
  7018. }
  7019. public T peek()
  7020. {
  7021. return deque.peek();
  7022. }
  7023. public T poll()
  7024. {
  7025. return deque.poll();
  7026. }
  7027. public int size()
  7028. {
  7029. return deque.size();
  7030. }
  7031. } // class LIFOQueue
  7032. /**
  7033. * The implementation of {@link #newSetFromMap(Map)}.
  7034. *
  7035. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  7036. * @since 1.6
  7037. */
  7038. private static class MapSet<E>
  7039. extends AbstractSet<E>
  7040. {
  7041. /**
  7042. * The backing map.
  7043. */
  7044. private Map<E,Boolean> map;
  7045. /**
  7046. * Constructs a new {@link MapSet} using the specified
  7047. * backing {@link Map}.
  7048. *
  7049. * @param map the backing map.
  7050. * @throws IllegalArgumentException if the map is not empty.
  7051. */
  7052. public MapSet(Map<E,Boolean> map)
  7053. {
  7054. if (!map.isEmpty())
  7055. throw new IllegalArgumentException("The map must be empty.");
  7056. this.map = map;
  7057. }
  7058. public boolean add(E e)
  7059. {
  7060. return map.put(e, true) == null;
  7061. }
  7062. public boolean addAll(Collection<? extends E> c)
  7063. {
  7064. boolean result = false;
  7065. final Iterator<? extends E> it = c.iterator();
  7066. while (it.hasNext())
  7067. result |= (map.put(it.next(), true) == null);
  7068. return result;
  7069. }
  7070. public void clear()
  7071. {
  7072. map.clear();
  7073. }
  7074. public boolean contains(Object o)
  7075. {
  7076. return map.containsKey(o);
  7077. }
  7078. public boolean isEmpty()
  7079. {
  7080. return map.isEmpty();
  7081. }
  7082. public Iterator<E> iterator()
  7083. {
  7084. return map.keySet().iterator();
  7085. }
  7086. public boolean remove(Object o)
  7087. {
  7088. return map.remove(o) != null;
  7089. }
  7090. public int size()
  7091. {
  7092. return map.size();
  7093. }
  7094. } // class MapSet
  7095. } // class Collections