+ All Categories
Home > Documents > ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview...

ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview...

Date post: 12-Jan-2016
Category:
Upload: antonia-cole
View: 213 times
Download: 0 times
Share this document with a friend
61
ADSA: Collections/4 241-423 Advanced Data Structures and Algorithms Objective give an overview of Collection classes, and create/use a Bag class Semester 2, 2013-2014 4. Collection Types
Transcript
Page 1: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 1

241-423 Advanced Data Structures and Algorithms

• Objective– give an overview of Collection classes, and

create/use a Bag class

Semester 2, 2013-2014

4. Collection Types

Page 2: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 2

Contents

1. What is a Collection?

2. (Some of ) Ford & Topp's Collections

3. The Bag Class

4. Sieve of Eratosthenes

5. Implementing the Bag Class

6. Iterators

7. The JDK's Collection Classes

Page 3: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 3

1. What is a Collection?

• A collection is an object that stores other objects.

• It includes operations for adding and removing objects and for accessing and updating their data.

Page 4: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 4

2. (Some of ) Ford & Topp's Collections

= interface/abstract class

= (concrete) class

implements/extends

OrderedListOrderedList

Page 5: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 5

The Collection Interface

interface Collection<T> ds.util boolean add(T element)

Ensures that this collection contains element; returns true if the operation performs an insertion and false if this collection does not permit duplicates and already contains the specified element.

void clear() Removes all of the elements from the collection. The collection is empty after the method returns.

continued

Page 6: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 6

interface Collection<T> ds.util boolean contains(Object element)

Returns true if this collection contains element and false otherwise.

boolean isEmpty() Returns true if this collection contains no elements and false if the collection has at least 1 element.

Iterator<T> iterator() Returns an iterator over the elements in this collection. The order in which elements are returned depends on the implementing class.

continued

I'll explain iterators ina later part.

Ford &Topp 'error'; not mine

Page 7: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 7

interface Collection<T> ds.util boolean remove(Object element)

If element is present in the collection, removes a single instance of the element from this collection. Returns true if an element was removed and false otherwise.

int size() Returns the number of elements in this collection

Object[] toArray() Returns an array containing all of the elements in this collection

Page 8: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 8

The List Interface

• The List interface extends the Collection interface by adding index-based operations.

• These allow for insertion, deletion, access, and updates at an index position in the list.

Page 9: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 9

The ArrayList Class

• An ArrayList stores element in a contiguous block of memory (like an array).

• But it is dynamic– it automatically expands when new elements are inserted

• An ArrayList is a direct-access structure– an operation can directly access any element

continued

Page 10: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 10

• Inserts and deletes at the right hand end of the list are O(1)

• Operations at other positions are O(n) since the rest of the list must be moved– shifted right for insertion– shifted left for deletion

Page 11: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 11

The LinkedList Class

• A LinkedList is a sequence whose elements are directly linked to adjacent elements in the sequence.

• A LinkedList is a sequential- access structure– an operation must move through the list to reach a particular element

continued

Page 12: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 12

• Insertion or deletion involves altering the links that connect the elements in the list– O(1) operations

•The OrderedList class is an extension of the List The OrderedList class is an extension of the List class that stores its elements in order. class that stores its elements in order.

Page 13: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 13

The Set Class• A Set is a collection of elements where duplicates

are not allowed.

• Includes mathematical set operations such as union, intersection, and difference.

setA ∩ setB

Page 14: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 14

The Map Class• A Map is a collection of key-value pairs

– the key uniquely identifies the pair while the value field holds its data (another object)

• Access to a pair requires the key, and returns the value.

• A Map is often called an associative array.

Page 15: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 15

The Stack Class

• An element can only be added (pushed) and removed (popped) from the top of the stack.

• Elements come off a stack in the reverse order of their insertion – a stack has a Last-In-First-Out (LIFO) ordering

Page 16: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 16

The Queue Class

• Items enter the queue at the back and exit from the front.

• Elements come off a queue in the same order as their insertion – a queue has First-In-First-Out (FIFO) ordering

Page 17: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 17

The Priority Queue• A priority queue is just like a queue, except for its

removal operation. – the operation removes the maximum (or minimum)

value, depending on the type of the priority queue

Page 18: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 18

The Graph and DiGraph Classes• A Graph is a set of vertices connected by links,

called edges. The edges may have weights.

• A digraph has directed edges.

Page 19: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 19

3. The Bag Class

• A Bag may contain duplicate elements (unlike a Set).

• grab() returns a random element from the collection.

Page 20: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 20

Using Bag

Find distinct characters in an input string and display them in alphabetical order.

Enter a string: mississippiSorted letters: [i, m, p, s]

m sip

bag A

m

iii

i

sss

s

pp

i m p s

bag B

array

grab

add

remove dups

sort

Page 21: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 21

Code

import ds.util.Bag;import ds.util.Arrays;import java.util.Scanner;

public class UseBag{ public static void main(String[] args) { Scanner keyIn = new Scanner(System.in); :

Page 22: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 22

// prompt for input string System.out.print("Enter a string: "); String str = keyIn.next();

// create bags big enough for input string Bag<Character> bagA = new Bag<Character>( str.length() ); Bag<Character> bagB = new Bag<Character>( str.length() );

// add chars from input string to bagA for (int i = 0; i < str.length(); i++) bagA.add(str.charAt(i)); :

Page 23: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 23

Character ch; boolean foundDuplicate;

while (!bagA.isEmpty()) { // move a random char from bagA to bagB ch = bagA.grab(); bagB.add(ch);

// remove all other occurrences of char from bagA do foundDuplicate = bagA.remove(ch); while (foundDuplicate); } :

Page 24: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 24

// create array from bagB; sort it; output Object[] objArr = bagB.toArray(); Arrays.sort(objArr); System.out.println("Sorted letters: " + Arrays.toString(objArr)); } // end of main()

} // end of UseBag class

Page 25: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 25

4. Sieve of Eratosthenes

• The Sieve of Eratosthenes uses a bag to find all primes ≤ an integer n.

• It begins by creating a bag for all the values from 2 to n.

• Then it removes all multiples of 2, 3, 4, etc. from the bag.

• Eventually only prime numbers are left.

continued

air – a – toss – the - neesair – a – toss – the - nees

Page 26: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 26

• The sieve of Eratosthenes finding all the prime numbers in the range 2 to 25:

array isn't a good d.s. choice due to space wastage

Page 27: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 27

Using the Sieve

import ds.util.Bag;

public class UseSieve{ public static void main(String[] args) { Bag<Integer> bag = sieve(500); Object[] arr = bag.toArray(); Arrays.sort(arr); writePrimes(arr); }

Display all primes from 2 to 500.

Page 28: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 28

public static Bag<Integer> sieve(int n){ Bag<Integer> primeBag = new Bag<Integer>(n);

// fill the set with integers 2, 3, ..., n for (int m = 2; m <= n; m++) primeBag.add( new Integer(m) ); :

Page 29: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 29

// find the primes from 2 to sqrt(n) for (int m = 2; m*m <= n; m++) { // if m is in the set then remove its multiples if(primeBag.contains( new Integer(m) )) { // make i go through 2*m, 3*m, ... int i = 2*m; while (i <= n) { primeBag.remove( new Integer(i) ); i += m; // set i to next m multiple } } } return primeBag;} composite is k*j == n

if k > then j must be <

composite is k*j == n

if k > then j must be <

nnnnaaa

n n

Page 30: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 30

public static void writePrimes(Object[] arr) // nicely print the array elements { String intStr; int count = 1; StringBuffer sb = new StringBuffer(" "); for (int i=0; i < arr.length; i++) { intStr = arr[i].toString(); // int --> string

// place intStr into string buffer, then print sb.replace(0, intStr.length(), intStr); System.out.print(sb.toString()); :

Page 31: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 31

// every 10 elements output a newline if(count % 10 == 0) System.out.println(); count++; } System.out.println(); } // end of writePrimes()

} // end of UseSieve class

Page 32: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 32

Execution

2 3 5 7 11 13 17 19 23 2931 37 41 43 47 53 59 61 67 7173 79 83 89 97 101 103 107 109 113127 131 137 139 149 151 157 163 167 173179 181 191 193 197 199 211 223 227 229233 239 241 251 257 263 269 271 277 281283 293 307 311 313 317 331 337 347 349353 359 367 373 379 383 389 397 401 409419 421 431 433 439 443 449 457 461 463467 479 487 491 499

Page 33: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 33

5. Implementing the Bag Class

public class Bag<T> implements Collection<T>{ private T[] bagArr; // storage private int bagSize; // size of collection

private Random rnd; // used by grab() :

The Bag class uses a fixed-size array as its storage structure.

Page 34: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 34

public Bag(int capacity) { bagArr = (T[])new Object[capacity]; bagSize = 0; rnd = new Random(); }

public String toString(){ Object[] arr = toArray(); // copy elems into an array return Arrays.toString(arr); // return array as a string}

Page 35: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 35

public boolean remove(Object item){ for (int i=0; i < bagSize; i++) if (bagArr[i].equals(item)) { // find item remove(i); return true; } return false;}

private void remove(int i)/* Remove bagArr[i] by moving the array elems left one position and decrementing bag size */{ for (int j=i; j < bagSize-1; j++) bagArr[j] = bagArr[j+1]; // copy elems to left bagSize--;}

Page 36: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 36

public boolean add(T item){ if (bagSize >= bagArr.length) // bag is full return false; else { // add item at end of bag bagArr[bagSize] = item; bagSize++; return true; }} // end of add()

public T grab()// return random value from bag in range (0,bagSize){ if (bagSize == 0) // bag is empty return null; else return bagArr[rnd.nextInt(bagSize)];} // end of grab()

} // end of Bag class

Page 37: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 37

6. Iterators

• An iterator is an object that can access the elements of a collection in an efficient and simple manner.– making data public in a collection is not simple

laterlater

Page 38: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 38

• The Iterator interface defines the methods that are available to an iterator.

• Every collection data structure that implements the Collection interface also implements the Iterator interface– e.g. List has a ListIterator

The Iterator Interface

continuedcontinued

Page 39: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 39continuedcontinued

Page 40: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 40

• An iterator for a collection is created by the Collection.iterator() method– it returns an Iterator object that points to the

beginning of the collection

continuedcontinued

Page 41: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 41

• Create a collection:// create a linked list of integersLinkedList<Integer> aList = ...;

• Create an iterator() for the collection that you want to scan:

Iterator<Integer> iter = aList.iterator();

• Collection.iterator() is called a factory method – a non-constructor method that creates objects

Page 42: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 42

Iterator Methods

• Iterator.hasNext() indicates whether more values remain in a collection scan.

// continue while there are remaining elementswhile (iter.hasNext()){ ... }

Ford & Topp's iter arrows are misleading; I've changed them.

later ...

Page 43: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 43

• Iterator.next() returns the value of the next collection element and moves forward to just after the next element.– calling next() when hasNext() is false results in a

NoSuchElementException

continuedcontinued

Page 44: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 44

• Standard code for scanning a collection:

// initialize iter to start of collection c

iter = c.iterator();

// loop through elements to end of collection

while (iter.hasNext()) {

value = iter.next(); // get value and move forward

// do something with value

}

continuedcontinued

Page 45: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 45

• The Iterator method remove() applied after a call to next() removes the collection value that was previously returned by next().

Page 46: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 46

Iterator Interface API

interface Iterator<T> ds.util

Methods boolean hasNext()

Returns true if the iteration has more elements

T next() Returns the next element in the list and moves this iterator forward one position

void remove() Removes from the underlying collection the last element returned by a call to the iterator method next()

Page 47: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 47

Using an Iterator

• Any collection class that implements the Collection interface must include iterators.

• An algorithm that relies on scanning (traversing) elements in a collection and extracting their values can be implemented using an iterator.

Page 48: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 48

max()public static <T extends Comparable<? super T>

T max (Collection c)

{ // create an iterator positioned at list start

Iterator<T> iter = c.iterator();

// assign maxValue the value of the first

// element and advance iter

T maxValue = iter.next();

// scan the rest of the elements in the collection

while (iter.hasNext()) {

T val = iter.next();

if (val.compareTo(maxValue) > 0)

maxValue = val;

}

return maxValue;

}

Page 49: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 49

7. The JDK's Collection Classes

• The Java JDK contains two high level Interfaces related to collections:– java.util.Collection– java.util.Map

• Collections are used for collecting Java objects. Maps are used for mapping key/value pairs.

Page 50: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 50

The Collection Interface

• Use a Collection if you need to keep related objects together, and want to:– search for a particular element– list the elements– manipulate the order of the elements– access the elements by an index number– use collection basic operations, such as add,

remove, update

Page 51: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 51

Set, List, and Queue Interfaces

Page 52: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 52

List in more Detail (JDK 6)

Page 53: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 53

Set in more Detail (JDK 6)

NavigableSet: a set with navigation methodsNavigableSet: a set with navigation methods

Page 54: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 54

Queue in more Detail (JDK 6)

deque (deck): insert/remove at both endsdeque (deck): insert/remove at both ends

Page 55: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 55

The Map Interface

• Use the Map interface to store <key, value> pairs, and you want to:– access an element by a key object– map one object to other

• A Map can be thought of as an array where the index need not be an integer.– also called associated array, dictionary

Page 56: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 56

Map in Detail (JDK 6)

Page 57: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 57

Thread-safe Collections

• Many collection classes have implementations for both single-threaded programs (no concurrency) and multiple threaded programs (concurrent).

continued

Also called concurrent collections.

Page 58: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 58

List in Full

Also Vector (but old fashioned)Also Vector (but old fashioned)

Page 59: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 59

Set in Full

Page 60: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 60

Queue in Full (very full)

BlockingQueue: v.useful for message passing BlockingQueue: v.useful for message passing

between threadsbetween threads

Page 61: ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

ADSA: Collections/4 61

Map in Full

Also Hashtable (but old fashioned)Also Hashtable (but old fashioned)


Recommended