Introduction To The Collections Framework: Tutorials
Introduction To The Collections Framework: Tutorials
Page 1 of 26
Tutorials
by MageLang Institute
[AboutThisCourse|Magercises] ThisshortcoursewillteachyouhowtousetheCollectionsFrameworkasfoundintheJava2platform.
Course Outline
IntroductiontotheCollectionsFramework MathematicalBackground CollectionInterfacesandClasses CollectionInterface IteratorInterface GroupOperations AbstractCollectionClass CollectionFrameworkDesignConcerns SetInterface HashSet,TreeSetClasses SetUsageExample AbstractSetClass ListInterface ListIteratorInterface ArrayList,LinkedListClasses ListUsageExample AbstractListandAbstractSequentialListClasses MapInterface Map.EntryInterface HashMap,TreeMapClasses MapUsageExample AbstractMapClass WeakHashMapClass Sorting ComparableInterface ComparatorInterface SortedSetInterface SortedMapInterface SpecialCollectionImplementations Read-OnlyCollections Thread-SafeCollections SingletonCollections MultipleCopyCollections EmptyCollections HistoricalCollectionClasses Arrays VectorandStackClasses EnumerationInterface Dictionary,Hashtable,PropertiesClasses BitSetClass AlgorithmSupport SortingArrays Searching CheckingEquality Manipulating Big-ONotation UsageIssues ConvertingfromHistoricalCollectionstoNewCollections
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 2 of 26
Mathematical Background
Incommonusageacollectionisthesameastheintuitive,mathamaticalconceptofaset.Asetisjustagroupofunique items,meaningthatthegroupcontainsnoduplicates.TheCollectionsFrameworkinfactincludesaSetinterface,anda numberofconcreteSetclasses.ButtheformalnotionofasetpredatesJavatechnologybyacentury,whentheBritish mathematicianGeorgeBooledefineditinformallogic.Mostpeoplelearnedsomesettheoryinelementaryschoolwhen introducedto"setintersection"and"setunion"throughthefamiliarVennDiagrams:
Somereal-worldexamplesofsetsincludethefollowing: Thesetofuppercaseletters'A'through'Z' Thesetofnonnegativeintegers{0,1,2...} ThesetofreservedJavaprogramminglanguagekeywords{'import','class','public','protected'...} Asetofpeople(friends,employees,clients,...) Thesetofrecordsreturnedbyadatabasequery ThesetofComponentobjectsinaContainer Thesetofallpairs Theemptyset{} Theseexamplesshowthebasicpropertiesofsets:
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 3 of 26
Setscontainsonlyoneinstanceofeachitem Setsmaybefiniteorinfinite Setscandefineabstractconcepts Setsarefundamentaltologic,mathematics,andcomputerscience,butalsopracticalineverydayapplicationsin businessandsystems.Theideaofa"connectionpool"isasetofopenconnectionstoadatabaseserver.Webservers havetomanagesetsofclientsandconnections.Filedescriptorsprovideanotherexampleofasetintheoperating system. Amapisaspecialkindofset.Itisasetofpairs,eachpairrepresentingaone-directional"mapping"fromoneelementto another.Someexamplesofmapsare: ThemapofIPaddressestodomainnames(DNS) Amapfromkeystodatabaserecords Adictionary(wordsmappedtomeanings) Theconversionfrombase2tobase10 Likesets,theideabehindamapismucholderthantheJavaprogramminglanguage,oldereventhancomputerscience. Setsandmapsareimportanttoolsinmathematicsandtheirpropertiesarewell-understood.Peoplealsolongrecognized theusefulnessofsolvingprogrammingproblemswithsetsandmaps.AlanguagecalledSETL(SetLanguage)invented in1969includedsetsasoneofitsonlyprimitivedatatypes(SETLalsoincludedgarbagecollection--notwidelyaccepted untilJavatechnologydevelopedinthe1990's).AlthoughsetsandmapsappearinmanylanguagesincludingC++,the CollectionsFrameworkisperhapsthebestdesignedsetandmappackageyetwrittenforapopularlanguage.Usersof C++StandardTemplateLibrary(STL)andSmalltalk'scollectionhierarchymightarguethatlastpoint. Alsobecausetheyaresets,mapscanbefiniteorinfinite.Anexampleofaninfinitemapistheconversionfrombase2to base10.Unfortunately,theCollectionsFrameworkdoesnotsupportinfatuatemaps--sometimesamathematicalfunction, formulaoralgorithmispreferred.Butwhenaproblemcanbesolvedwithafinitemap,theCollectionsFramework providestheJavaprogrammerwithausefulAPI. BecausetheCollectionsFrameworkhasformaldefinitionsfortheclassesSet,Collection,andMap,you'llnoticethe lowercasewordsset,collectionandmaptodistinguishtheimplementationfromtheconcept.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 4 of 26
operationsofget()andput()whicharenotrequiredbySet.Moreover,therearemethodsthatreturnSetviewsof Mapobjects: Set set = aMap.keySet(); WhendesigningsoftwarewiththeCollectionsFramework,itisusefultorememberthefollowinghierarchicalrelationships ofthefourbasicinterfacesoftheframework: TheCollectioninterfaceisagroupofobjects,withduplicatesallowed SetextendsCollectionbutforbidsduplicates ListextendsCollectionalso,allowsduplicatesandintroducespositionalindexing MapextendsneitherSetnorCollection Movingontotheframeworkimplementations,theconcretecollectionclassesfollowanamingconvention,combiningthe underlyingdatastructurewiththeframeworkinterface.Thefollowingtableshowsthesixcollectionimplementations introducedwiththeJava2framework,inadditiontothefourhistoricalcollectionclasses.Forinformationonhowthe historicalcollectionclasseschanged,likehowHashtablewasreworkedintotheframework,seetheHistorical CollectionClassessection,below. Interface Set List Map HashSet HashMap Implementation ArrayList TreeSet TreeMap LinkedList Historical Vector Stack Hashtable Properties
Collection Interface
TheCollectioninterfaceisusedtorepresentanygroupofobjects,orelements.Youusetheinterfacewhenyouwish toworkwithagroupofelementsinasgeneralamanneraspossible.HereisalistofthepublicmethodsofCollection inUnifiedModelingLanguage(UML)notation.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 5 of 26
boolean remove(Object element) TheCollectioninterfacealsosupportsqueryoperations: int size() boolean isEmpty() boolean contains(Object element) Iterator iterator() Iterator Interface Theiterator()methodoftheCollectioninterfacereturnsanIterator.AnIteratorissimilartothe Enumerationinterface,whichyoumayalreadybefamiliarwith,andwillbedescribedlater.WiththeIterator interfacemethods,youcantraverseacollectionfromstarttofinishandsafelyremoveelementsfromtheunderlying Collection:
Collection collection = ...; Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); if (removalCheck(element)) { iterator.remove(); } }
Group Operations OtheroperationstheCollectioninterfacesupportsaretasksdoneongroupsofelementsortheentirecollectionat once: boolean containsAll(Collection collection) boolean addAll(Collection collection) void clear() void removeAll(Collection collection) void retainAll(Collection collection) ThecontainsAll()methodallowsyoutodiscoverifthecurrentcollectioncontainsalltheelementsofanother collection,asubset.Theremainingmethodsareoptional,inthataspecificcollectionmightnotsupportthealteringofthe collection.TheaddAll()methodensuresallelementsfromanothercollectionareaddedtothecurrentcollection, usuallyaunion.Theclear()methodremovesallelementsfromthecurrentcollection.TheremoveAll()methodis likeclear()butonlyremovesasubsetofelements.TheretainAll()methodissimilartotheremoveAll() method,butdoeswhatmightbeperceivedastheopposite.Itremovesfromthecurrentcollectionthoseelementsnotin theothercollection,anintersection. Theremainingtwointerfacemethods,whichconvertaCollectiontoanarray,willbediscussedlater. AbstractCollection Class
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 6 of 26
TheAbstractCollectionclassprovidesthebasisfortheconcretecollectionframeworkclasses.Whileyouarefree toimplementallthemethodsoftheCollection interfaceyourself,theAbstractCollectionclassprovides implementationsforallthemethods,exceptfortheiterator()andsize()methods,whichareimplementedinthe appropriatesubclass.Optionalmethodslikeadd()willthrowanexceptionifthesubclassdoesn'toverridethebehavior. Collection Framework Design Concerns InthecreationoftheCollectionsFramework,theSundevelopmentteamneededtoprovideflexibleinterfacesthat manipulatedgroupsofelements.Tokeepthedesignsimple,insteadofprovidingseparateinterfacesforoptional capabilities,theinterfacesdefineallthemethodsanimplementationclassmayprovide.However,someoftheinterface methodsareoptional.Becauseaninterfaceimplementationmustprovideimplementationsforalltheinterfacemethods, thereneededtobeawayforacallertoknowifanoptionalmethodisnotsupported.Themannertheframework developmentteamchosetosignalcallerswhenanoptionalmethodiscalledwastothrownan UnsupportedOperationException.Ifinthecourseofusingacollection,anUnsupportedOperationException isthrown,liketryingtoaddtoaread-onlycollection,thentheoperationfailedbecauseitisnotsupported.Toavoid havingtoplaceallcollectionoperationswithinatry-catchblock,theUnsupportedOperationExceptionclassis anextensionoftheRuntimeExceptionclass. Inadditiontohandlingoptionaloperationswitharuntimeexception,theiteratorsfortheconcretecollection implementationsarefail-fast.ThatmeansthatifyouareusinganIteratortotraverseacollectionwhileunderlying collectionisbeingmodifiedbyanotherthread,thentheIteratorfailsimmediatelybythrowinga ConcurrentModificationException(anotherRuntimeException).ThatmeansthenexttimeanIterator methodiscalled,andtheunderlyingcollectionhasbeenmodified,theConcurrentModificationException exceptiongetsthrown.
Set Interface
TheSetinterfaceextendstheCollectioninterfaceand,bydefinition,forbidsduplicateswithinthecollection.Allthe originalmethodsarepresentandnonewmethodsareintroduced.TheconcreteSetimplementationclassesrelyonthe equals()methodoftheobjectaddedtocheckforequality.
HashSet, TreeSet Classes TheCollectionsFrameworkprovidestwogeneral-purposeimplementationsoftheSetinterface:HashSetandTreeSet. Moreoftenthannot,youwilluseaHashSetforstoringyourduplicate-freecollection.Forefficiency,objectsaddedtoa HashSetneedtoimplementthehashCode()methodinamannerthatproperlydistributesthehashcodes.Whilemost systemclassesoverridethedefaulthashCode()implementationinObject,whencreatingyourownclassestoaddtoa HashSetremembertooverridehashCode().TheTreeSetimplementationisusefulwhenyouneedtoextract elementsfromacollectioninasortedmanner.Inordertoworkproperty,elementsaddedtoaTreeSetmustbe sortable.TheCollectionsFrameworkaddssupportforComparableelementsandwillbecoveredindetaillater.Fornow, justassumeatreeknowshowtokeepelementsofthejava.langwrapperclassessorted.Itisgenerallyfastertoadd elementstoaHashSet,thenconvertthecollectiontoaTreeSetforsortedtraversal.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 7 of 26
import java.util.*; public class SetExample { public static void main(String args[]) { Set set = new HashSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set.add("Clara"); System.out.println(set); Set sortedSet = new TreeSet(set); System.out.println(sortedSet); } }
Runningtheprogramproducesthefollowingoutput.Noticethattheduplicateentryisonlypresentonce,andthesecond listoutputissorted. [Gene, Clara, Bernadine, Elizabeth] [Bernadine, Clara, Elizabeth, Gene] AbstractSet Class TheAbstractSetclassoverridestheequals()andhashCode()methodstoensuretwoequalsetsreturnthesame hashcode.Twosetsareequaliftheyarethesamesizeandcontainthesameelements.Bydefinition,thehashcodefor asetisthesumofthehashcodesfortheelementsoftheset.Thus,nomatterwhattheinternalorderingofthesets,two equalsetswillreportthesamehashcode.
Magercises
1. UsingaHashSetforaSparseBitSet 2. UsingaTreeSettoprovideasortedJList
List Interface
TheListinterfaceextendstheCollectioninterfacetodefineanorderedcollection,permittingduplicates.The interfaceaddsposition-orientedoperations,aswellastheabilitytoworkwithjustapartofthelist.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 8 of 26
Theposition-orientedoperationsincludetheabilitytoinsertanelementorCollection,getanelement,aswellas removeorchangeanelement.SearchingforanelementinaListcanbestartedfromthebeginningorendandwill reportthepositionoftheelement,iffound. void add(int index, Object element) boolean addAll(int index, Collection collection) Object get(int index) int indexOf(Object element) int lastIndexOf(Object element) Object remove(int index) Object set(int index, Object element) TheListinterfacealsoprovidesforworkingwithasubsetofthecollection,aswellasiteratingthroughtheentirelistina positionfriendlymanner: ListIterator listIterator() ListIterator listIterator(int startIndex) List subList(int fromIndex, int toIndex) InworkingwithsubList(),itisimportanttomentionthattheelementatfromIndexisinthesublist,buttheelementat toIndexisnot.Thislooselymapstothefollowingfor-looptestcases: for (int i=fromIndex; i<toIndex; i++) { // process element at position i } Inaddition,itshouldbementionedthatchangestothesublist[likeadd(),remove(),andset()calls]haveaneffect ontheunderlyingList. ListIterator Interface TheListIteratorinterfaceextendstheIteratorinterfacetosupportbi-directionalaccess,aswellasaddingor changingelementsintheunderlyingcollection.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 9 of 26
Thefollowingsourcecodedemonstratestheloopingbackwardsthroughalist.NoticethattheListIteratoris originallypositionedbeyondtheendofthelist[list.size()],astheindexofthefirstelementis0. List list = ...; ListIterator iterator = list.listIterator(list.size()); while (iterator.hasPrevious()) { Object element = iterator.previous(); // Process element } Normally,onedoesn'tuseaListIteratortoalternatebetweengoingforwardandbackwardinoneiterationthrough theelementsofacollection.Whiletechnicallypossible,oneneedstoknowthatcallingnext()immediatelyafter previous()resultsinthesameelementbeingreturned.Thesamethinghappenswhenyoureversetheorderofthe callstonext()andprevious(). Theadd()operationrequiresalittlebitofexplanation,also.Addinganelementresultsinthenewelementbeingadded immediatelypriortotheimplicitcursor.Thus,callingprevious()afteraddinganelementwouldreturnthenewelement andcallingnext()wouldhavenoeffect,returningwhatwouldhavebeenthenextelementpriortotheaddoperation. ArrayList, LinkedList Classes Therearetwogeneral-purposeListimplementationsintheCollectionsFramework:ArrayListandLinkedList. WhichofthetwoListimplementationsyouusedependsonyourspecificneeds.Ifyouneedtosupportrandomaccess, withoutinsertingorremovingelementsfromanyplaceotherthantheend,thanArrayListofferstheoptimalcollection. If,however,youneedtofrequentlyaddandremoveelementsfromthemiddleofthelistandonlyaccessthelistelements sequentiallythenLinkedListoffersthebetterimplementation. BothArrayListandLinkedListimplementtheCloneableinterface.Inaddition,LinkedListaddsseveral methodsforworkingwiththeelementsattheendsofthelist(onlythenewmethodsareshowninthefollowingdiagram):
Byusingthesenewmethods,youcaneasilytreattheLinkedListasastack,queue,orotherend-orienteddata structure. LinkedList queue = ...; queue.addFirst(element); Object object = queue.removeLast(); LinkedList stack = ...;
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 10 of 26
stack.addFirst(element); Object object = stack.removeFirst(); TheVectorandStackclassesarehistoricalimplementationsoftheListinterface.Theywillbediscussedlater. List Usage Example ThefollowingprogramdemonstratestheuseoftheconcreteListclasses.ThefirstpartcreatesaListbackedbyan ArrayList.Afterfillingthelist,specificentriesareretrieved.TheLinkedListpartoftheexampletreatsthe LinkedListasaqueue,addingthingsatthebeginningofthequeueandremovingthemfromtheend.
import java.util.*; public class ListExample { public static void main(String args[]) { List list = new ArrayList(); list.add("Bernadine"); list.add("Elizabeth"); list.add("Gene"); list.add("Elizabeth"); list.add("Clara"); System.out.println(list); System.out.println("2: " + list.get(2)); System.out.println("0: " + list.get(0)); LinkedList queue = new LinkedList(); queue.addFirst("Bernadine"); queue.addFirst("Elizabeth"); queue.addFirst("Gene"); queue.addFirst("Elizabeth"); queue.addFirst("Clara"); System.out.println(queue); queue.removeLast(); queue.removeLast(); System.out.println(queue); } }
Runningtheprogramproducesthefollowingoutput.Noticethat,unlikeSet,Listpermitsduplicates. [Bernadine, Elizabeth, Gene, Elizabeth, Clara] 2: Gene 0: Bernadine [Clara, Elizabeth, Gene, Elizabeth, Bernadine] [Clara, Elizabeth, Gene] AbstractList and AbstractSequentialList Classes TherearetwoabstractListimplementationsclasses:AbstractListandAbstractSequentialList.Likethe AbstractSetclass,theyoverridetheequals()andhashCode()methodstoensuretwoequalcollectionsreturnthe samehashcode.Twosetsareequaliftheyarethesamesizeandcontainthesameelementsinthesameorder.The hashCode()implementationisspecifiedintheListinterfacedefinitionandimplementedhere. Besidestheequals()andhashCode()implementations,AbstractListandAbstractSequentialListprovide partialimplementationsoftheremainingListmethods.Theymakethecreationofconcretelistimplementationseasier, forrandom-accessandsequential-accessdatasources,respectively.Whichsetofmethodsyouneedtodefinedepends onthebehavioryouwishtosupport.Thefollowingtableshouldhelpyourememberwhichmethodsneedtobe implemented.Onethingyou'llneverneedtoprovideyourselfisanimplementationoftheIterator iterator() method. unmodifiable AbstractList Object get(int index) int size() AbstractSequentialList ListIterator listIterator(int index) - boolean hasNext() - Object next()
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 11 of 26
modifiable
unmodifiable+ Object set(int index, Object element) modifiable+ add(int index, Object element) Object remove(int index)
variable-size andmodifiable
- int nextIndex() - boolean hasPrevious() - Object previous() - int previousIndex() int size() unmodifiable+ ListIterator - set(Object element) modifiable+ ListIterator - add(Object element) - remove()
AstheCollectioninterfacedocumentationstates,youshouldalsoprovidetwoconstructors,ano-argumentoneand onethatacceptsanotherCollection.
Magercise
3. UsinganArrayListwithaJComboBox
Map Interface
TheMapinterfaceisnotanextensionoftheCollectioninterface.Instead,theinterfacestartsoffitsowninterface hierarchy,formaintainingkey-valueassociations.Theinterfacedescribesamappingfromkeystovalues,without duplicatekeys,bydefinition.
Theinterfacemethodscanbebrokendownintothreesetsofoperations:altering,querying,andprovidingalternative views. Thealterationoperationsallowyoutoaddandremovekey-valuepairsfromthemap.Boththekeyandvaluecanbe null.However,youshouldnotaddaMaptoitselfasakeyorvalue. Object put(Object key, Object value) Object remove(Object key) void putAll(Map mapping) void clear() Thequeryoperationsallowyoutocheckonthecontentsofthemap: Object get(Object key) boolean containsKey(Object key) boolean containsValue(Object value) int size() boolean isEmpty() Thelastsetofmethodsallowyoutoworkwiththegroupofkeysorvaluesasacollection.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 12 of 26
public Set keySet() public Collection values() public Set entrySet() Sincethecollectionofkeysinamapmustbeunique,yougetaSetback.Sincethecollectionofvaluesinamapmay notbeunique,yougetaCollectionback.ThelastmethodreturnsaSetofelementsthatimplementtheMap.Entry interface,describednext. Map.Entry Interface TheentrySet()methodofMapreturnsacollectionofobjectsthatimplementMap.Entryinterface.Eachobjectinthe collectionisaspecifickey-valuepairintheunderlyingMap.
Iteratingthroughthiscollection,youcangetthekeyorvalue,aswellaschangethevalueofeachentry.However,theset ofentriesbecomesinvalid,causingtheiteratorbehaviortobeundefined,iftheunderlyingMapismodifiedoutsidethe setValue()methodoftheMap.Entryinterface. HashMap, TreeMap Classes TheCollectionsFrameworkprovidestwogeneral-purposeMapimplementations:HashMapandTreeMap.Aswithallthe concreteimplementations,whichimplementationyouusedependsonyourspecificneeds.Forinserting,deleting,and locatingelementsinaMap,theHashMapoffersthebestalternative.If,however,youneedtotraversethekeysina sortedorder,thenTreeMapisyourbetteralternative.Dependinguponthesizeofyourcollection,itmaybefastertoadd elementstoaHashMap,thenconvertthemaptoaTreeMapforsortedkeytraversal.UsingaHashMaprequiresthatthe classofkeyaddedhaveawell-definedhashCode()implementation.WiththeTreeMapimplementation,elements addedtothemapmustbesortable.Again,moreonsortinglater. TooptimizeHashMapspaceusage,youcantunetheinitialcapacityandloadfactor.TheTreeMaphasnotuning options,asthetreeisalwaysbalanced. BothHashMapandTreeMapimplementtheCloneableinterface. TheHashtableandPropertiesclassesarehistoricalimplementationsoftheMapinterface.Theywillbediscussed later. Map Usage Example ThefollowingprogramdemonstratestheuseoftheconcreteMapclasses.Theprogramgeneratesafrequencycountof wordspassedfromthecommandline.AHashMapisinitiallyusedfordatastorage.Afterwards,themapisconvertedtoa TreeMaptodisplaythekeylistsorted.
import java.util.*; public class MapExample { public static void main(String args[]) { Map map = new HashMap(); Integer ONE = new Integer(1); for (int i=0, n=args.length; i<n; i++) { String key = args[i]; Integer frequency = (Integer)map.get(key); if (frequency == null) {
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 13 of 26
frequency = ONE; } else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(key, frequency); } System.out.println(map); Map sortedMap = new TreeMap(map); System.out.println(sortedMap); } }
RunningtheprogramwiththethetextfromArticle3oftheBillofRightsproducesthefollowingoutput.Noticehowmuch moreusefulthesortedoutputlooks. Unsorted {prescribed=1, a=1, time=2, any=1, no=1, shall=1, nor=1, peace=1, owner=1, soldier=1, to=1, the=2, law=1, but=1, manner=1, without=1, house=1, in=4, by=1, consent=1, war=1, quartered=1, be=2, of=3} andsorted {a=1, any=1, be=2, but=1, by=1, consent=1, house=1, in=4, law=1, manner=1, no=1, nor=1, of=3, owner=1, peace=1, prescribed=1, quartered=1, shall=1, soldier=1, the=2, time=2, to=1, war=1, without=1} AbstractMap Class Similartotheotherabstractcollectionimplementations,theAbstractMapclassoverridestheequals()and hashCode()methodstoensuretwoequalmapsreturnthesamehashcode.Twomapsareequaliftheyarethesame size,containthesamekeys,andeachkeymapstothesamevalueinbothmaps.Bydefinition,thehashcodeforamap isthesumofthehashcodesfortheelementsofthemap,whereeachelementisanimplementationoftheMap.Entry interface.Thus,nomatterwhattheinternalorderingofthemaps,twoequalmapswillreportthesamehashcode. WeakHashMap Class AWeakHashMapisaspecial-purposeimplementationofMapforstoringonlyweakreferencestothekeys.Thisallowsfor thekey-valuepairsofthemaptobegarbagecollectedwhenthekeyisnolongerreferencedoutsideofthe WeakHashMap.UsingWeakHashMapisbeneficialformaintainingregistry-likedatastructures,wheretheutilityofan entryvanisheswhenitskeyisnolongerreachablebyanythread. TheJava2SDK,StandardEdition,version1.3addsaconstructortoWeakHashMapthatacceptsaMap.Withversion1.2 oftheJava2platform,theavailableconstructorsonlypermitoverridingthedefaultloadfactorandinitialcapacitysetting, notinitializingthemapfromanothermap(asrecommendedbytheMapinterfacedocumentation).
Sorting
TherehavebeenmanychangestothecoreJavalibrariestoaddsupportforsortingwiththeadditionoftheCollections FrameworktotheJava2SDK,version1.2.ClasseslikeStringandIntegernowimplementtheComparable interfacetoprovideanaturalsortingorder.Forthoseclasseswithoutanaturalorder,orwhenyoudesireadifferentorder thanthenaturalorder,youcanimplementtheComparatorinterfacetodefineyourown. Totakeadvantageofthesortingcapabilities,theCollectionsFrameworkprovidestwointerfacesthatuseit:SortedSet andSortedMap. Comparable Interface TheComparableinterface,inthejava.langpackage,isforwhenaclasshasanaturalordering.Givenacollectionof objectsofthesametype,theinterfaceallowsyoutoorderthecollectionintothatnaturalordering.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 14 of 26
ThecompareTo()methodcomparesthecurrentinstancewithanelementpassedinasanargument.Ifthecurrent instancecomesbeforetheargumentintheordering,anegativevalueisreturned.Ifthecurrentinstancecomesafter, thenapositivevalueisreturned.Otherwise,zeroisreturned.Itisnotarequirementthatazeroreturnvaluesignifies equalityofelements.Azeroreturnvaluejustsignifiesthattwoobjectsareorderedatthesameposition. TherearefourteenclassesintheJava2SDK,version1.2,thatimplementstheComparableinterface.Thefollowing tableshowstheirnaturalordering.Whilesomeclassessharethesamenaturalordering,youcanonlysortclassesthat aremutually comparable.ForthecurrentreleaseoftheSDK,thatmeansthesameclass. Class BigDecimal BigInteger Byte Double Float Integer Long Short Character CollationKey Date File ObjectStreamField String Ordering
Numerical
import java.text.*; import java.util.*; public class CollatorTest { public static void main(String args[]) { Collator collator = Collator.getInstance(); CollationKey key1 = collator.getCollationKey("Tom"); CollationKey key2 = collator.getCollationKey("tom"); CollationKey key3 = collator.getCollationKey("thom"); CollationKey key4 = collator.getCollationKey("Thom"); CollationKey key5 = collator.getCollationKey("Thomas"); Set set = new TreeSet(); set.add(key1); set.add(key2); set.add(key3); set.add(key4); set.add(key5); printCollection(set);
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 15 of 26
} static private void printCollection( Collection collection) { boolean first = true; Iterator iterator = collection.iterator(); System.out.print("["); while (iterator.hasNext()) { if (first) { first = false; } else { System.out.print(", "); } CollationKey key = (CollationKey)iterator.next(); System.out.print(key.getSourceString()); } System.out.println("]"); } }
Runningtheprogramproducesthefollowingoutput: [thom, Thom, Thomas, tom, Tom] Ifthenameswerestoreddirectly,withoutusingCollator,thenthelowercasenameswouldappearapartfromthe uppercasenames: [Thom, Thomas, Tom, thom, tom] MakingyourownclassComparableisjustamatterofimplementingthecompareTo()method.Itusuallyinvolves relyingonthenaturalorderingofseveraldatamembers.Yourownclassesshouldalsooverrideequals()and hashCode()toensuretwoequalobjectsreturnthesamehashcode. Comparator Interface Whenaclasswasn'tdesignedtoimplementjava.lang.Comparable,youcanprovideyourown java.util.Comparator.ProvidingyourownComparatoralsoworksifyoudon'tlikethedefaultComparable behavior.
Thereturnvaluesofthecompare()methodofComparatoraresimilartothecompareTo()methodofComparable. Inthiscase,ifthefirstelementcomesbeforethesecondelementintheordering,anegativevalueisreturned.Ifthefirst elementcomesafter,thenapositivevalueisreturned.Otherwise,zeroisreturned.SimilartoComparable,azeroreturn valuedoesnotsignifyequalityofelements.Azeroreturnvaluejustsignifiesthattwoobjectsareorderedatthesame position.ItsuptotheuseroftheComparatortodeterminehowtodealwithit.Iftwounequalelementscomparetozero, youshouldfirstbesurethatiswhatyouwantandseconddocumentthebehavior.UsingaComparatorthatisnot compatibletoequalscanbedeadlywhenusedwithaTreeSetorTreeMap.Withaset,onlythefirstwillbeadded.With amap,thevalueforthesecondwillreplacethevalueforthesecond(keepingthekeyofthefirst). Todemonstrate,youmayfinditeasiertowriteanewComparatorthatignorescase,insteadofusingCollatortodoa locale-specific,case-insensitivecomparison.Thefollowingisonesuchimplementation:
class CaseInsensitiveComparator implements Comparator { public int compare(Object element1, Object element2) { String lowerE1 = (
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 16 of 26
Magercise
4. UsingaMaptoCountWords SortedSet Interface TheCollectionsFrameworkprovidesaspecialSetinterfaceformaintainingelementsinasortedorder:SortedSet.
Theinterfaceprovidesaccessmethodstotheendsofthesetaswellastosubsetsoftheset.Whenworkingwithsubsets ofthelist,changestothesubsetarereflectedinthesourceset.Inaddition,changestothesourcesetarereflectedinthe subset.Thisworksbecausesubsetsareidentifiedbyelementsattheendpoints,notindices.Inaddition,ifthe fromElementispartofthesourceset,itispartofthesubset.However,ifthetoElementispartofthesourceset,itis notpartofthesubset.Ifyouwouldlikeaparticularto-elementtobeinthesubset,youmustfindthenextelement.Inthe caseofaString,thenextelementisthesamestringwithanullcharacterappended(string+"\0").; TheelementsaddedtoaSortedSetmusteitherimplementComparableoryoumustprovideaComparatortothe constructorofitsimplementationclass:TreeSet.(Youcanimplementtheinterfaceyourself.ButtheCollections Frameworkonlyprovidesonesuchconcreteimplementationclass.) Todemonstrate,thefollowingexampleusesthereverseorderComparatoravailablefromtheCollectionsclass:
Comparator comparator = Collections.reverseOrder(); Set reverseSet = new TreeSet(comparator); reverseSet.add("Bernadine"); reverseSet.add("Elizabeth"); reverseSet.add("Gene"); reverseSet.add("Elizabeth"); reverseSet.add("Clara"); System.out.println(reverseSet);
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 17 of 26
Comparator comparator = new CaseInsensitiveComparator(); Set set = new TreeSet(comparator); set.add("Tom"); set.add("tom"); set.add("thom"); set.add("Thom"); set.add("Thomas");
Read-Only Collections
Afteryou'veaddedallthenecessaryelementstoacollection,itmaybeconvenienttotreatthatcollectionasread-only,to preventtheaccidentalmodificationofthecollection.Toprovidethiscapability,theCollectionsclassprovidessix factorymethods,oneforeachofCollection,List,Map,Set,SortedMap,andSortedSet. Collection unmodifiableCollection(Collection collection) List unmodifiableList(List list) Map unmodifiableMap(Map map) Set unmodifiableSet(Set set) SortedMap unmodifiableSortedMap(SortedMap map)
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 18 of 26
import java.util.*; public class ReadOnlyExample { public static void main(String args[]) { Set set = new HashSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set = Collections.unmodifiableSet(set); set.add("Clara"); } }
Whenrunandthelastadd()operationisattemptedontheread-onlyset,anUnsupportedOperationExceptionis thrown.
Thread-Safe Collections
ThekeydifferencebetweenthehistoricalcollectionclassesandthenewimplementationswithintheCollections Frameworkisthenewclassesarenotthread-safe.Thiswasdonesuchthatifyoudon'tneedthesynchronization,you don'tuseit,andeverythingworksmuchfaster.If,however,youareusingacollectioninamulti-threadedenvironment, wheremultiplethreadscanmodifythecollectionsimultaneously,themodificationsneedtobesynchronized.The Collectionsclassprovidesforthetheabilitytowrapexistingcollectionsintosynchronizedoneswithanothersetofsix methods: Collection synchronizedCollection(Collection collection) List synchronizedList(List list) Map synchronizedMap(Map map) Set synchronizedSet(Set set) SortedMap synchronizedSortedMap(SortedMap map) SortedSet synchronizedSortedSet(SortedSet set) Unlikewhenmakingacollectionread-only,yousynchronizethecollectionimmediatelyaftercreatingit.Youalsomust makesureyoudonotretainareferencetotheoriginalcollection,orelseyoucanaccessthecollectionunsynchronized. Thesimplestwaytomakesureyoudon'tretainareferenceistonevercreateone: Set set = Collection.synchronizedSet(new HashSet()); Makingacollectionunmodifiablealsomakesacollectionthread-safe,asthecollectioncan'tbemodified.Thisavoidsthe synchronizationoverhead.
Singleton Collections
TheCollectionsclassprovidesfortheabilitytocreatesingleelementsetsfairlyeasily.Insteadofhavingtocreatethe Setandfillitinseparatesteps,youcandoitallatonce.TheresultingSetisimmutable. Set set = Collection.singleton("Hello"); TheJava2SDK,StandardEdition,version1.3addstheabilitytocreatesingletonlistsandmaps,too: List singletonList(Object element) Map singletonMap(Object key, Object value)
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 19 of 26
Ifyouneedanimmutablelistwithmultiplecopiesofthesameelement,thenCopies(int n, Object element) methodoftheCollectionsclassreturnsjustsuchtheList: List fullOfNullList = Collection.nCopies(10, null); Byitself,thatdoesn'tseemtoouseful.However,youcanthenmakethelistmodifiablebypassingitalongtoanotherlist: List anotherList = new ArrayList(fullOfNullList); Thisnowcreates10elementArrayList,whereeachelementisnull.Youcannowmodifyeachelementatwill,asit becomesappropriate.
Empty Collections
TheCollectionsclassalsoprovidesconstantsforemptycollections: List EMPTY_LIST Set EMPTY_SET TheJava2SDK,StandardEdition,version1.3hasapredefinedemptymapconstant: Map EMPTY_MAP
Arrays
OnelearnsaboutarraysfairlyearlyonwhenlearningtheJavaprogramminglanguage.Arraysaredefinedtobefixedsizecollectionsofthesamedatatype.Theyaretheonlycollectionthatsupportsstoringprimitivedatatypes.Everything else,includingarrays,canstoreobjects.Whencreatinganarray,youspecifyboththenumberandtypeofobjectyou wishtostore.And,overthelifeofthearray,itcanneithergrownorstoreadifferenttype(unlessitextendsthefirsttype). Tofindoutthesizeofanarray,youaskitssinglepublicinstancevariable,length,asinarray.length. Toaccessaspecificelement,eitherforsettingorgetting,youplacetheintegerargumentwithinsquarebrackets ([int]),eitherbeforeorafterthearrayreferencevariable.Theintegerindexiszero-based,andaccessingbeyondeither endofthearraywillthrownanArrayIndexOutOfBoundsExceptionatruntime.If,however,youusealongvariable toaccessanarrayindex,you'llgetacompiler-timeerror. Arraysarefull-fledgedsubclassesofjava.lang.Object.TheycanbeusedwiththevariousJavaprogramming languageconstructsexceptinganobject:
Object obj = new int[5]; if (obj instanceof int[]) { // true } if (obj.getClass().isArray()) { // true }
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 20 of 26
System.arraycopy(Object sourceArray, int sourceStartPosition, Object destinationArray, int destinationStartPosition, int length)
Enumeration Interface
TheEnumerationinterfaceallowsyoutoiteratorthroughalltheelementsofacollection.IntheCollectionsFramework, thisinterfacehasbeensupercededbytheIteratorinterface.However,notalllibrariessupportsthenewerinterface, soyoumayfindyourselfusingEnumerationfromtimetotime.
IteratingthroughanEnumerationissimilartoiteratingthroughanIterator,thoughsomepeoplelikethemethod namesbetterwithIterator.However,thereisnoremovalsupportwithEnumeration. Enumeration enum = ...; while (enum.hasNextElement()) { Object element = iterator.nextElement(); // process element }
BitSet Class
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 21 of 26
Magercise
5. UsingaHashSetforaSparseBitSet
Algorithm Support
TheCollectionsandArraysclasses,availableaspartoftheCollectionsFramework,providesupportforvarious algorithmswiththecollectionclasses,bothnewandold.Thedifferentoperations,startingwithsortingandsearching,are describednext.
Sorting Arrays
WhiletheTreeSetandTreeMapclassesoffersortedversionofsetsandmaps,thereisnosortedListcollection implementation.Also,priortothecollectionsframework,therewasnobuiltinsupportforsortingarrays.Aspartofthe framework,yougetbothsupportforsortingaList,aswellassupportforsortingarraysofanything,includingprimitives. Withanykindofsorting,allitemsmustbecomparabletoeachother(mutually comparable).Iftheyarenot,a ClassCastExceptionwillbethrown. SortingofaListisdonewithoneoftwosort()methodsintheCollectionsclass.Iftheelementtypeimplements Comparablethenyouwouldusethesort(List list)version.Otherwise,youwouldneedtoprovidea Comparatorandusesort(List list, Comparator comparator).BothversionsaredestructivetotheList andguaranteeO(n log2n)performance(orbetter),includingwhensortingaLinkedList,usingamergesort variation. Sortingofarraysisdonewithoneofeighteendifferentmethods.Therearetwomethodsforsortingeachoftheseven primitivetypes(besidesboolean),oneforsortingthewholearrayandoneforsortingpartofthearray.Theremaining fourareforsortingobjectarrays(Object[ ]). ThesortingofprimitivearraysinvolvingjustcallingArrays.sort()withyourarrayastheargument,andlettingthe compilerdeterminewhichofthefollowingmethodstopick: void void void void void void void void void void void void void void sort(byte array[ ]) sort(byte array[ ], int fromIndex, int toIndex) sort(short array[ ]) sort(short array[ ], int fromIndex, int toIndex) sort(int array[ ]) sort(int array[ ], int fromIndex, int toIndex) sort(long array[ ]) sort(long array[ ], int fromIndex, int toIndex) sort(float array[ ]) sort(float array[ ], int fromIndex, int toIndex) sort(double array[ ]) sort(double array[ ], int fromIndex, int toIndex) sort(char array[ ]) sort(char array[ ], int fromIndex, int toIndex)
Thesortingofobjectarraysisalittlemoreinvolved,asthecompilerdoesn'tcheckeverythingforyou.Iftheobjectinthe arrayimplementsComparable,thenyoucanjustsortthearraydirectly,inwholeorinpart.Otherwise,youmustprovide aComparatortodothesortingforyou.YoucanalsoprovideaComparatorimplementationifyoudon'tlikethedefault ordering. void void void void sort(Object sort(Object sort(Object sort(Object array[ array[ array[ array[ ]) ], int fromIndex, int toIndex) ], Comparator comparator) ], int fromIndex, int toIndex, Comparator comparator)
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 22 of 26
Searching
Besidessorting,theCollectionsandArraysclassesprovidemechanismstosearchaListorarray,aswellasto findtheminimumandmaximumvalueswithinaCollection. Whileyoucanusethecontains()methodofListtofindifanelementispartofthelist,itassumesanunsortedlist.If you'vepreviouslysortedtheList,usingCollections.sort(),thenyoucandoamuchquickerbinarysearchusing oneofthetwooverriddenbinarySearch()methods.IftheobjectsintheListimplementComparable,thenyou don'tneedtoprovideaComparator.Otherwise,youmustprovideaComparator.Inaddition,ifyousortedwitha Comparator,youmustusethesameComparatorwhenbinarysearching. public static int binarySearch(List list, Object key) public static int binarySearch(List list, Object key, Comparator comparator) IftheListtosearchsubclassestheAbstractSequentialListclass(likeLinkedList),thenasequentialsearchis actuallydone. Arraysearchingworksthesameway.AfterusingoneoftheArrays.sort()methods,youcantaketheresultingarray andsearchforanelement.TherearesevenoverriddenvarietiesofbinarySearch()tosearchforaprimitive(allbut boolean),andtwotosearchanObjectarray,bothwithandwithoutaComparator. IftheoriginalListorarrayisunsorted,theresultisnon-deterministic. BesidessearchingforspecificelementswithinaList,youcansearchforextremeelementswithinanyCollection: theminimumandmaximum.Ifyouknowyourcollectionisalreadysorted,justgetthefirstorlastelement.However,for unsortedcollections,youcanuseoneofthemin()ormax()methodsofCollections.Iftheobjectinthecollection doesn'timplementComparable,thenyoumustprovideaComparator. Object Object Object Object max(Collection max(Collection min(Collection min(Collection collection) collection, Comparator comparator) collection) collection, Comparator comparator)
Checking Equality
WhiletheMessageDigestclassalwaysprovidedanisEqual()methodtocomparetwobytearrays,itneverfeltright touseittocomparebytearraysunlesstheywerefrommessagedigests.Now,withthehelpoftheArraysclass,you cancheckforequalityofanyarrayofprimitiveorobjecttype.Twoarraysareequaliftheycontainthesameelementsin thesameorder.Checkingforequalitywitharraysofobjectsreliesontheequals()methodofeachobjecttocheckfor equality. byte array1[] = ...; byte array2[] = ...; if (Arrays.equals(array1, array2) { // They're equal }
Manipulating
TheCollectionsandArraysclassesofferseveralwaysofmanipulatingtheelementswithinaListorarray.There arenoadditionalwaystomanipulatetheotherkeyframeworkinterfaces(SetandMap). WithaList,theCollectionsclassletsyoureplaceeveryelementwithasingleelement,copyanentirelistto another,reversealltheelements,orshufflethemaround.Whencopyingfromonelisttoanother,ifthedestinationlistis larger,theremainingelementsareuntouched. void void void void void fill(List list, Object element) copy(List source, List destination) reverse(List list) shuffle(List list) shuffle(List list, Random random)
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 23 of 26
Big-O Notation
PerformanceofsortingandsearchingoperationswithcollectionsofsizenismeasuredusingBig-Onotation.The notationdescribesthecomplexityofthealgorithminrelationtothemaximumtimeinwhichanalgorithmoperates,for largevaluesofn.Forinstance,ifyouiteratethroughanentirecollectiontofindanelement,theBig-Onotationisreferred toasO(n),meaningthatasnincreases,timetofindanelementinacollectionofsizenincreaseslinearly.This demonstratesthatBig-Onotationassumesworstcaseperformance.Itisalwayspossiblethatperformanceisquicker. ThefollowingtableshowstheBig-Ovaluesfordifferentoperations,with65,536asthevalueforn.Inaddition,the operationcountshowsthatifyouaregoingtoperformmultiplesearchoperationsonacollection,itisfastertodoaquick sortonthecollection,priortosearching,versusdoingalinearsearcheachtime.(And,oneshouldavoidbubblesorting, unlessnisreallysmall!)
Usage Issues
TheCollectionsFrameworkwasdesignedsuchthatthenewframeworkclassesandthehistoricaldatastructureclasses caninteroperate.Whileitisgoodifyoucanhaveallyournewcodeusethenewframework,sometimesyoucan't.The frameworkprovidesmuchsupportforintermixingthetwosetsofcollections.Inaddition,youcandevelopwithasubsetof thecapabilitieswithJDK1.1.
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 24 of 26
Enumeration enumeration = ...; Collection collection = new LinkedList(); while (e.hasMoreElements()) { collection.add(e.nextElement()); } // Operate on collection
Dimension dims[] = {new Dimension (0,0), new Dimension (0,0)}; List list = Arrays.asList(dims); Vector v = new Vector(list); Dimension d = (Dimension)v.get(1); d.width = 12;
GoingfromCollectiontoEnumerationismucheasierthangoingfromEnumerationtoCollection.The Collectionsclassincludesastaticmethodtodotheconversionforyou: Collection collection = ...; Enumeration enum = Collections.enumeration(collection); TheconversionfromMaptoHashtableissimilartoCollectiontoVector,justpassthenewframeworkclasstothe constructor.Aftertheconversion,changingthevalueforthekeyinonedoesnotalterthevalueforthekeyintheother. Map map = ...; Hashtable hashtable = new Hashtable(map);
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 25 of 26
movedfromthejava.langandjava.utilpackagetothenon-corecom.sun.java.util.collectionspackage. Thisisnotacompletesetofclasseschangedtosupporttheframework,butonlycopiesofthoseintroduced.Basically, whatthatmeansisnoneofthesystemclassesaresortablebydefault,youmustprovideyourownComparator. ThefollowingtableliststheclassesavailableintheCollectionsFrameworkreleaseforJDK1.1.Insomecases,therewill betwodifferentimplementationsofthesameclass,likewithVector,asthe1.2frameworkversionimplementsList andthecore1.1versiondoesn't. AbstractCollection AbstractMap AbstractSet Arrays Collections Comparator HashMap Hashtable LinkedList ListIterator NoSuchElementException Set SortedSet TreeSet Vector AbstractList AbstractSequentialList ArrayList Collection Comparable ConcurrentModificationException HashSet Iterator List Map Random SortedMap TreeMap UnsupportedOperationException
Alternative Collections
BecausetheCollectionFrameworkwasnotavailablepriortotheintroductionoftheJava2platform,severalalternative collectionlibrariesbecameavailable.TwosuchlibrariesareDougLea'sCollectionsPackageandObjectSpace'sJGL.
ObjectSpace's JGL
InadditiontoDougLea'scollectionslibrary,theGenericCollectionLibraryforJava(JGL)fromObjectSpacewasanearly collectionlibrariesavailablefortheJavaplatform.FollowingthedesignpatternsoftheStandardTemplateLibrary(STL) forC++,thelibraryprovidesalgorithmicsupport,inadditiontoadatastructurelibrary.WhiletheJGLisagoodalternative collectionframework,itdidn'tmeetthedesigngoalsoftheCollectionsFrameworkteam:"Themaindesigngoalwasto produceanAPIthatwasreasonablysmall,bothinsize,and,moreimportantly,inconceptual weight."Withthatinmind, theteamcameupwiththeCollectionsFramework. WhilenotadoptedbySunMicrosystems,theJGLhasbeenincludedwithmanyIDEtool.Duetoitsearlyavailability,the JGLisavailabletowellover100,000developers. ForacomparisonofJGLversustheCollectionsFramework,seeThebattleofthecontainerframeworks:whichshould youuse?articleinJavaWorld.[Ifyouarecuriousofhowthelibrarynamemapstotheacronym,itdoesn't.Thenameof thefirstversionofthelibraryinfringedonSun'sJavatrademark.ObjectSpacechangedthename,buttheoriginal acronymstuck.]
Conclusion
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011
Page 26 of 26
Resources
Thefollowingresources,somepulledfromthecoursenotes,shouldhelpinyourusageandunderstandingofthe CollectionsFramework: HowtoBuildDataStructuresinJava-aJavaDeveloperConnectionJDCarticlefrompriortotheexistenceofthe CollectionFramework Design Patternsbook-ErichGamma,RichardHelm,RalphJohnson,andJohnVlissides(TheGangofFour) CollectionsFrameworkSupportforJDK1.1 DougLea'sCollectionsPackage GenericCollectionLibraryforJava-JGLfromObjectSpace Thebattleofthecontainerframeworks:whichshouldyouuse?-JavaWorldarticlefromJanuary1999 Sun'sCollectionsFrameworkHome Copyright1999MageLangInstitute.AllRightsReserved.
copyrightSunMicrosystems,Inc
http://java.sun.com/jsp_utils/PrintPage.jsp?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fjava.sun.com%2Fdevelo... 5/11/2011