Dates & ListsDate classesDateDateFormatSlide 5CalendarExampleFundamental AbstractionsCollection InterfacesCollectionSetListIteratorModifying CollectionsIterator ExampleListIteratorSlide 17Collection APIBulk Operation ExampleList APISublist ExampleImplementationsArrayListLinkedListBenchmarksSortingComparable interfaceComparatorReturn valueCollections MethodsSlide 31Dates & ListsIS 313, 4.8.2003Date classesDaterepresents a point in timeDateFormata class (abstract) that formats time and date informationCalendara class (abstract) that allows for date arithmeticDatecurrent timeDate d = new Date ()other datesgo through DateFormat or CalendarDateFormatUse static factory methodsDateFormat.getDateInstanceCan specify short, medium, long or fullDateFormat.getDateInstance (DateFormat.SHORT)Can also specific localeDateFormat.getDateInstance(DateFormat.SHORT, Locale.ITALY)SimpleDateFormat for custom formatsnew SimpleDateFormat (“MM/dd/yyyy”)DateFormatWith the date formatparse strings containing datesoutput strings containing datesParseDate date = df.parse (“11/12/1999”);FormatString dateString = df.format (date);CalendarDate/Calendar arithmeticWhat day of the week was 2/23/1995?What was the date 30 days later?Different calendarswe use GregorianCalendarExampleDateDateFormatSimpleDateFormatCalendarGregorianCalendarFundamental AbstractionsCollectionAny grouping of itemsSetUnordered, non-redundantListOrderedMapObject->Object mappingsCollection InterfacesCollectionPerform operations that apply to any collectionIn many casesDistinction between Set and List is irrelevantAdd an itemTest to see if an Object is in the CollectionSome operations not supported by all implementationsSetHas only the Collection methodsBut the Collection has no duplicatesListAdds to the Collection methodsPositional accessSearchRange-viewAn enhanced IteratorIteratorMoves through the elements of a Collection“consuming” = “moving”like reading data from a streamMethodshasNext(), next()remove()last item seenModifying CollectionsIterator is like a pointer within the collection, butpoints “in between” entriesModificationhappens to last visited entryIterator ExampleListIteratorSpecific to List objectsSet and addAs well as removeAdds backward movementiter.prev();modification still happens to last visited itemIterator Examplestatic void filter(Collection c) {for (Iterator i = c.iterator(); i.hasNext(); ) if (i.next().toString().indexOf(“Burke”) == -1)i.remove();} What does it do?Works on any collection“for” skeletonCollection APIint size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]);Bulk Operation Examplec.removeAll(new Integer(0)); Remove all 0s from a Collection of Integer objectsMore about the Collections class laterList API// Positional Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); // Optional Object remove(int index); // Optional boolean addAll(int index, Collection c); // Optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator listIterator(); ListIterator listIterator(int index); // Range-view List subList(int from, int to);Sublist Examplepublic static List dealHand(List deck, int n){int deckSize = deck.size();List handView = deck.subList(deckSize-n, deckSize);List hand = new ArrayList(handView);handView.clear();return hand;}ImplementationsInterfaces do not give us objectsNeed specific implementations to do what the interfaces specifyJava has multiple implementations for most interfacesReasonPerformance tradeoffsArrayListVector-likeO(n) delete and insertexcept at endGood for most purposesLinkedListSlower at positional accessO(n) vs O(1)Insert / remove advantageBenchmarksType Get Iteration Insert RemoveArrayList 110 270 1920 4780LinkedList 1870 7580 170 110SortingCollectionsutility methods include sortingCollections.sort (c)To sort, we need an orderWhat takes precedence over whatNo universal order possibleComparable interfacepublic interface Comparable{ public int compareTo(Object o);} Your class must implement in order to be sortableStatic method in Collections classCollections.sort (myCollection);errorif objects in myCollection don’t implement Comparableif contents of myCollection aren’t comparable to each otherComparatorComparable interface = “natural order”Sometimes multiple ordering possiblesA separate class called a comparatorpublic interface Comparator { int compare(Object o1, Object o2);}NoteComparable = 1 argument, Comparator = 2 argsReturn valueint return value-1 means “less than”0 means “equal”should match ==+1 means “greater than”in compareTo-1 means this < argumentin compare-1 means o1 < o2Collections
View Full Document