Set and MapTuesday’s codeSkeletonsHomeworkResourcesHomework #1Homework 1 Solution StructureHomework #1 Solution StructurePart 2 Solution StructureMain ProgramGeneral AdviceStringTokenizerStringTokenizer cont’dExampleSlide 15Fundamental AbstractionsCollection InterfacesSetRemove DuplicatesSortedSetSortedSet APISlide 22MapMap APICollection ViewsViewsSortedMapImplementationsHashSetHash TableTo store a set in a hash tableTreeSetBinary TreeTo store a set in a binary treeTrade-offsHashMapTo store a map in a hash tableTreeMapTo store a map in a binary treeDecoratorsSlide 41Slide 42Set and MapIS 313, 1.16.2002Tuesday’s codeComparatorSkeletonsUseful coding patternsShould understandhow and why they workhow to usepossible quiz materialHomeworkLate policy10% per dayonly if help requested 48 hrs in advanceAcademic honestyNo code sharingBUT discussion and assistance is OKRule of thumbAm I getting advice? Or a homework solution?NotePlagiarized code is (surprisingly) easy to detectResourcesHomework discussion forumEmail to instructorif you need to get advice on a large chunk of codeHomework #1Frequent Flyer ProgramInputA file of member accountsA file of flightsOutputA updated file of member accountsnote: must be sorted by member nameHomework 1 Solution StructureMember classimplement comparableor, separate CompareByName comparatorMemberMap to hold Membersencapsulates a SortedMap access by idFlightstores flight information including encapsulates List of member #sHomework #1 Solution StructureFlightListencapsulates a Listall of the flight objects in the fileMemberUpdater“main” classshould be VERY simplePart 2 Solution StructureCapacityInfo classEncapsulated SortedMapassociating dates with capacity dataMain ProgramVery simplepublic class MemberUpdater{public void main (String [] args){MemberList members = new MemberList ();members.load (“accounts.dat”);FlightList flights = new FlightList ();flights.load (“flights.dat”);members.updateForFlights (flights);members.save (“updated.dat”);}}General AdviceStart earlyworking on homework = studying for quizImplement Member firstUse instantiation skeleton (#1 and #2) to create from fileDon’t cut cornersall 6 classes are neededStringTokenizerUseful for handling text filesBreaks strings into tokensusually defined by whitespace“words”StringTokenizer cont’dWorks like an iteratorTest for completionhasMoreTokensGet token and movenextTokenSkeleton #2 shows how to use a StringTokenizer to create objects from a text fileExampleString text = "Whatever you want, you'll get it.";StringTokenizer st = new StringTokenizer(text);while( st.hasMoreTokens() ) { String word = st.nextToken(); ...process token...}ExampleStringTokenizerFundamental AbstractionsCollectionAny grouping of itemsSetUnordered, non-redundantListOrderedMapObject->Object mappingsCollection InterfacesSetHas only the Collection methodsBut the Collection has no duplicatesRemove Duplicatespublic Object [] removeDups (Object [] ar){List original = Arrays.asList (ar);Set noDups = new HashSet(original);return noDups.toArray();}How does this work?Arrays utility classWill the returned array be in the same order as the original?SortedSetSet starts to look like a listElements are iterated over in orderLike sorting operationsObjects must be Comparable Or a Comparator can be suppliedSortedSet APIpublic interface SortedSet extends Set { // Range-view SortedSet subSet(Object fromElement, Object toElement);SortedSet headSet(Object toElement); SortedSet tailSet(Object fromElement); // Endpoints Object first(); Object last(); // Comparator access Comparator comparator();}ExampleSortedSetComparableMapCollection of pairsKey, valueWe can associate valuesname, phone numbermember id, member objectBoth key and value must be objectsuse “wrapper” classes for primitive typesmap.put (new Integer(5), “stored at 5”);Map APIObject put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet();Collection ViewskeySet()A set of the keysvalues()A collection of the valuesentrySet()A set of all the pairsEntry objectsgetKey, getValueViewsViews are still tied to the original MapIf I remove a key from the keySetIt is removed from the MapExamplem1.keySet().removeAll(m2.keySet()); Removes any entries in m1 that have the same key as an entry in m2.SortedMapExactly analogous to SortedSetSort is in key orderImplementationsSetHashSetTreeSetMapHashMapTreeMap(WeakHashMap)(LinkedHashMap)HashSetCollection implemented with a hash tableO(1) accessProvide you size it appropriatelyAn odd # about twice as big as the size of the largest setHash TableTo store a set in a hash tableUsehash key = the item in the setstored value = anythingIf there is an entry in the tablethe item is in the setTreeSetOnly useful for sorted setsO(log n) for accessbut it is always sortedBinary TreeTo store a set in a binary treeUsetree key = item in the setvalue = anythingIf the tree key is in the treethe item is in the setTo iterate in orderstart at the left of the tree“in-order” traversalTrade-offsSortingSizefor large collectionsHashMapO(1) accessSame size considerations as HashSetTo store a map in a hash tableUsehash key = map keyvalue = valueTo look up a valuefind the key/value pairreturn valueTreeMapOnly useful for SortedMapO(log n) accessTo store a map in a binary treeUsetree key = map keytree value = map valueTo look up a valuetraverse tree to appropriate keyreturn stored valueTo iterate“in-order” tranversalDecoratorsUnmodifiablePass in a normal collection (set, map, whatever)The resulting collection is the same but can’t be modifiedSynchronizedPass in a normal collectionThe resulting collection is synchronizedCan’t be shared between threadsUseful in multi-threaded programs, otherwise
View Full Document