35
Working With Collections in the AP Java Subset 2003 ACTE Convention © 2003 by Kenneth A. Lambert

Working With Collections in the AP ™ Java Subset 2003 ACTE Convention © 2003 by Kenneth A. Lambert

Embed Size (px)

Citation preview

Working With Collections in the AP™ Java Subset

2003 ACTE Convention

© 2003

by Kenneth A. Lambert

Presenter’s Information

Dr. Kenneth A. LambertDepartment of Computer ScienceWashington and Lee UniversityLexington, VA 24450

Email: [email protected] page: http://www.wlu.edu/~lambertk/These slides: http://www.wlu.edu/~lambertk/ACTE/

The Second Course in Computer Science

• Data structures

• Algorithms for processing data structures in various applications

• Analysis of performance of data structures and algorithms

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?

1999-2003:Data Structures in AP “AB”

• Arrays (also used to implement strings)

• Linked lists

• In C++– apstring– apvector– apmatrix– apstack– apqueue

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

Categories of Collections

• Linear

• Hierarchical

• Graph (not covered in second college course)

• Unordered

Linear Collections

• List• Stack• Queue D1 D2 D3

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

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

Unordered Collections

• Set• Bag• Map (table)

D4

D3

D5

D1 D2

• Objects are in no particular order• Implementations use hashing to approach constant-time access

Standard Java Collections

• Lists - linear, supporting many operations

• Sets - unordered, unique items

• Sorted sets - like sets, but items can be visited in sorted order

Standard Java Collections

• Maps - unordered, items accessed by keys

• Sorted maps - same as maps, but keys can be visited in sorted order

Non-Standard Collections

• Stacks

• Queues

• Priority queues

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 theusers. 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:

Multiple Implementations

ArrayList LinkedList

List

Client’s program

Implementingclasses

Interface

A client can choose among several implementations of the same ADT.

The client’s code looks the same, because it uses an interface.

Java Collection Interfaces

Collection

List Set Map

SortedSet SortedMap

SortedSet extends Set, which extends Collection

Java Collection Classes

AbstractCollection

AbstractList AbstractSet AbstractMap

HashSet HashMap

Object

AbstractSequentialList

TreeSet TreeMapArrayList LinkedList

= concrete class ( instantiated by clients)

= abstract class (organizes code in the server)

Non-Standard AP Collections

ArrayStack LinkedStack

Stack

Client’s program

Implementingclasses

Interface

Interfaces: Stack, Queue, and PriorityQueue

Implementing classes: whatever seems appropriate

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

// Create two stacks using different implementationsStack s1 = new ArrayStack();Stack s2 = new LinkedStack();

// Push some Integer objects onto s1 and some// String objects onto s2for (int i = 1; i <= 5; i++){ s1.push(new Integer(i)); s2.push("" + i);}

// Remove and display the contents of s1while (!s1.isEmpty()){ Object obj = s1.pop(); System.out.println(obj);}

// Cause an exception to be thrown by looking at top of s1System.out.println(s1.peekTop());

Using Stack Collections

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

// Create two lists using different implementationsList list1 = new ArrayList();List list2 = new LinkedList();

// Add some objects to the two lists. . .

// Display the contents of list1for (int i = 0; i list1.size(); i++) System.out.println(list1.get(i));

// Display the contents of list2for (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!!

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

collection iterator

A stream of elements

public boolean hasNext()

public Object next()

public void remove()

The Iterator Interface

remove deletes the object most recently accessedwith next

remove need not be supported, for example, with stacks

// 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.

The Collection Interface

Collection

List Set

SortedSet

List and Set extend the Collection interface, so a list or a set can be used wherever a collection is expected.

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 listList myList = new ArrayList(mySet);

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

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)

Not All Collections Implement Collection

Collection

List Set Map

SortedSet SortedMap

Stack Queue PriorityQueue

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.

A Collection-View Is Similar to an Iterator

backing storecollection

backing storecollection

iteratorobject

collection-viewobject

client usinghasNext, next

client usingremoveAll,retainAll,

etc.

A collection-view allows an object to masqueradeas a collection

The Method collectionView

Any class that implements collectionView will becompatible with the Collection interface withoutimplementing that interface.

Any class that implements collectionView should also include an iterator method.

Iterator iterator() // Returns an iterator

Collection collectionView() // Returns a collection-view

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 stackStack myStack = new ArrayStack(myList);

// Open a collection-view on the stackCollection colView = myStack.collectionView();

// Transfer the objects in the stack to a new listList anotherList = new LinkedList(colView);

Useful Resources

Textbook:

Fundamentals of Java Comprehensive (by Lambert & Osborne, Course Technology, 2003)

Web sites:

Textbook page: http://home.wlu.edu/~lambertk/hsjava/

AP Central: http://apps.apcentral.collegeboard.com/Login.jsp