Download presentation
Presentation is loading. Please wait.
Published byFelipe Downen Modified over 9 years ago
1
Working With Collections in the AP ™ Java Subset 2003 ACTE Convention © 2003 by Kenneth A. Lambert
2
Presenter’s Information Dr. Kenneth A. Lambert Department of Computer Science Washington and Lee University Lexington, VA 24450 Email: klambert@wlu.eduklambert@wlu.edu Home page: http://www.wlu.edu/~lambertk/http://www.wlu.edu/~lambertk/ These slides: http://www.wlu.edu/~lambertk/ACTE/http://www.wlu.edu/~lambertk/ACTE/
3
The Second Course in Computer Science Data structures Algorithms for processing data structures in various applications Analysis of performance of data structures and algorithms
4
Perspectives on Data Structures Formal properties –What are they? –How are they organized and classified? Implementations –How are they represented? –What are the performance trade-offs? Applications –What are they good for?
5
1999-2003: Data Structures in AP “AB” Arrays (also used to implement strings) Linked lists In C++ –apstring –apvector –apmatrix –apstack –apqueue
6
2004: Collections In Java, data structures are collections A collection is an object that contains other objects There are zero or more objects in a collection There are operations for accessing these objects
7
Categories of Collections Linear Hierarchical Graph (not covered in second college course) Unordered
8
Linear Collections List Stack Queue D1D2D3 0 1 2 Objects are ordered by position Each object except the first has a unique predecessor Each object except the last has a unique successor Access is more restricted for stacks and queues
9
Hierarchical Collections Binary tree General tree Binary search tree Heap D1 D2 D3 Each object except the root has a unique predecessor Each can have zero or more successors
10
Unordered Collections Set Bag Map (table) D4 D3 D5 D1D2 Objects are in no particular order Implementations use hashing to approach constant-time access
11
Standard Java Collections Lists - linear, supporting many operations Sets - unordered, unique items Sorted sets - like sets, but items can be visited in sorted order
12
Standard Java Collections Maps - unordered, items accessed by keys Sorted maps - same as maps, but keys can be visited in sorted order
13
Non-Standard Collections Stacks Queues Priority queues
14
Abstract Data Types (ADTs) Separate the user (client) of a collection from the implementer (server) A list can be implemented with an array or a linked structure, but this implementation is invisible to the users. The data and methods of an implementation are defined in a class. A list has a set of abstract operations for insertions, removals, etc. This set of operations is called an interface. Example:
15
Multiple Implementations ArrayListLinkedList List Client’s program Implementing classes Interface A client can choose among several implementations of the same ADT. The client’s code looks the same, because it uses an interface.
16
Java Collection Interfaces Collection ListSetMap SortedSetSortedMap SortedSet extends Set, which extends Collection
17
Java Collection Classes AbstractCollection AbstractListAbstractSetAbstractMap HashSetHashMap Object AbstractSequentialList TreeSetTreeMapArrayListLinkedList = concrete class ( instantiated by clients) = abstract class (organizes code in the server)
18
Non-Standard AP Collections ArrayStackLinkedStack Stack Client’s program Implementing classes Interface Interfaces: Stack, Queue, and PriorityQueue Implementing classes: whatever seems appropriate
19
public interface Stack{ // Returns true if the stack is empty or false otherwise public boolean isEmpty(); // Postcondition: obj is added to the top of the stack public void push(Object obj); // Precondition: the stack is not empty // Postcondition: the object is removed from the top of // the stack and returned to the client // Throws: IllegalStateException if the stack is empty public Object pop(); // Precondition: the stack is not empty // Postcondition: the object at the top of the stack is // returned to the client // Throws: IllegalStateException if the stack is empty public Object peekTop(); } The Stack Interface
20
// Create two stacks using different implementations Stack s1 = new ArrayStack(); Stack s2 = new LinkedStack(); // Push some Integer objects onto s1 and some // String objects onto s2 for (int i = 1; i <= 5; i++){ s1.push(new Integer(i)); s2.push("" + i); } // Remove and display the contents of s1 while (!s1.isEmpty()){ Object obj = s1.pop(); System.out.println(obj); } // Cause an exception to be thrown by looking at top of s1 System.out.println(s1.peekTop()); Using Stack Collections
21
Performance Analysis Each implementation of a collection has performance characteristics Each implementation can be measured for its running time and memory usage A wise client chooses the implementation whose performance most enhances the application
22
// Create two lists using different implementations List list1 = new ArrayList(); List list2 = new LinkedList(); // Add some objects to the two lists... // Display the contents of list1 for (int i = 0; i list1.size(); i++) System.out.println(list1.get(i)); // Display the contents of list2 for (int i = 0; i list2.size(); i++) System.out.println(list2.get(i)); Performance Tradeoffs Method get runs in linear time for linked lists, so traversals of linked lists using get run in quadratic time!!
23
Iterators An iterator allows the client to track a position in a collection and visit the object at that position Two basic operations –Test for more items –Get the next item collectioniterator A stream of elements
24
public boolean hasNext() public Object next() public void remove() The Iterator Interface remove deletes the object most recently accessed with next remove need not be supported, for example, with stacks
25
// Add some objects to list2... Iterator iter = list2.iterator(); while (iter.hasNext()){ Object obj = iter.next(); System.out.println(obj); } Using an Iterator The iterator method returns an object whose class implements the Iterator interface. Traversals of any list with an iterator take linear time.
26
The Collection Interface Collection ListSet SortedSet List and Set extend the Collection interface, so a list or a set can be used wherever a collection is expected.
27
Creating a Collection from Another Collection Define a constructor that expects an object of type Collection as a parameter Use an iterator in that constructor to access the collection’s objects Set mySet = new HashSet(); // Add some objects to mySet... // Transfer the objects in the set to a new list List myList = new ArrayList(mySet);
28
import java.util.*; public class LinkedStack implements Stack{ public LinkedStack(){ // Initialize the instance variables } public LinkedStack(Collection col){ this(); Iterator iter = col.iterator(); while (iter.hasNext()) push(iter.next()); } // Other method definitions // Instance variables } Example: Any Collection to Stack
29
The Collection Interface High-level operations Operations common to all collections boolean add(Object o) boolean addAll(Collection c) void clear() boolean contains(Object o) boolean containsAll(Collection c) boolean equals(Object o) int hashCode() boolean isEmpty() Iterator iterator() boolean remove(Object o) boolean removeAll(Collection c) boolean retainAll(Collection c) int size() Object[] toArray() Object[] toArray(Object[] a)
30
Not All Collections Implement Collection Collection ListSetMap SortedSetSortedMap StackQueuePriorityQueue
31
Collection-View A collection-view is an object that –implements the Collection interface –has a collection as a backing store which does not implement the collection interface –allows clients to use many of the Collection methods with such collections as stacks, queues, etc.
32
A Collection-View Is Similar to an Iterator backing store collection backing store collection iterator object collection-view object client using hasNext, next client using removeAll, retainAll, etc. A collection-view allows an object to masquerade as a collection
33
The Method collectionView Any class that implements collectionView will be compatible with the Collection interface without implementing that interface. Any class that implements collectionView should also include an iterator method. Iterator iterator() // Returns an iterator Collection collectionView()// Returns a collection-view
34
List to Stack and Stack to List List myList = new ArrayList(); // Add some objects to myList... // Transfer the objects in the list to a new stack Stack myStack = new ArrayStack(myList); // Open a collection-view on the stack Collection colView = myStack.collectionView(); // Transfer the objects in the stack to a new list List anotherList = new LinkedList(colView);
35
Useful Resources Textbook: Fundamentals of Java Comprehensive (by Lambert & Osborne, Course Technology, 2003) Web sites: Textbook page: http://home.wlu.edu/~lambertk/hsjava/http://home.wlu.edu/~lambertk/hsjava/ AP Central: http://apps.apcentral.collegeboard.com/Login.jsphttp://apps.apcentral.collegeboard.com/Login.jsp
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.