Dates & ListsDate classesDateDateFormatDateFormatCalendarExampleFundamental AbstractionsCollection InterfacesCollectionSetListIteratorModifying CollectionsIterator ExampleListIteratorIterator ExampleCollection APIBulk Operation ExampleList APISublist ExampleImplementationsArrayListLinkedListBenchmarksSortingComparable interfaceComparatorReturn valueCollections MethodsExampleDates & ListsIS 313, 4.8.2003Date classes Date represents a point in time DateFormat a class (abstract) that formats time and date information Calendar a class (abstract) that allows for date arithmeticDate current time Date d = new Date () other dates go through DateFormat or CalendarDateFormat Use static factory methodsDateFormat.getDateInstance Can 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”)DateFormat With the date format parse strings containing dates output strings containing dates ParseDate date = df.parse (“11/12/1999”); FormatString dateString = df.format (date);Calendar Date/Calendar arithmetic What day of the week was 2/23/1995? What was the date 30 days later? Different calendars we use GregorianCalendarExample Date DateFormat SimpleDateFormat Calendar GregorianCalendarFundamental Abstractions Collection Any grouping of items Set Unordered, non-redundant List Ordered Map Object->Object mappingsCollection InterfacesCollection Perform operations that apply to any collection In many cases Distinction between Set and List is irrelevant Add an item Test to see if an Object is in the Collection Some operations not supported by all implementationsSet Has only the Collection methods But the Collection has no duplicatesList Adds to the Collection methods Positional access Search Range-view An enhanced IteratorIterator Moves through the elements of a Collection “consuming” = “moving” like reading data from a stream Methods hasNext(), next() remove() last item seenModifying Collections Iterator is like a pointer within the collection, but points “in between” entries Modification happens to last visited entryIterator ExampleListIterator Specific to List objects Set and add As well as remove Adds backward movement iter.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 objects More 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;}Implementations Interfaces do not give us objects Need specific implementations to do what the interfaces specify Java has multiple implementations for most interfaces Reason Performance tradeoffsArrayList Vector-like O(n) delete and insert except at end Good for most purposesLinkedList Slower at positional access O(n) vs O(1) Insert / remove advantageBenchmarks11017075801870LinkedList47801920270110ArrayListRemoveInsertIterationGetTypeSorting Collections utility methods include sorting Collections.sort (c) To sort, we need an order What takes precedence over what No universal order possibleComparable interfacepublic interface Comparable{ public int compareTo(Object o);} Your class must implement in order to be sortable Static method in Collections class Collections.sort (myCollection); error if objects in myCollection don’t implement Comparable if contents of myCollection aren’t comparable to each otherComparator Comparable interface = “natural order” Sometimes multiple ordering possibles A separate class called a comparatorpublic interface Comparator { int compare(Object o1, Object o2);} Note Comparable = 1 argument, Comparator = 2 argsReturn value int return value -1 means “less than” 0 means “equal” should match == +1 means “greater than” in compareTo -1 means this < argument in compare -1 means o1 < o2Collections Methods binarySearch copy fill max min reverse shuffle singleton sortExample List ArrayList Iterator Collections.sort Comparable
View Full Document