Download presentation
Presentation is loading. Please wait.
Published byAntonia Cole Modified over 9 years ago
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 2, 2013-2014 4. Collection Types
2
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
3
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.
4
ADSA: Collections/4 4 2. (Some of ) Ford & Topp's Collections = interface/abstract class = (concrete) class implements/extends OrderedList
5
ADSA: Collections/4 5 The Collection Interface continued
6
ADSA: Collections/4 6 continued I'll explain iterators in a later part. Ford &Topp 'error'; not mine
7
ADSA: Collections/4 7
8
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.
9
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
10
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
11
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
12
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 class that stores its elements in order. The OrderedList class is an extension of the List class that stores its elements in order.
13
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
14
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.
15
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
16
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
17
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
18
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.
19
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.
20
ADSA: Collections/4 20 Using Bag Find distinct characters in an input string and display them in alphabetical order. Enter a string: mississippi Sorted letters: [i, m, p, s] ms i p bag A m i i i i s s s s p p imps bag B array grab add remove dups sort
21
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); :
22
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 bagA = new Bag ( str.length() ); Bag bagB = new Bag ( str.length() ); // add chars from input string to bagA for (int i = 0; i < str.length(); i++) bagA.add(str.charAt(i)); :
23
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); } :
24
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
25
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 - nees
26
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
27
ADSA: Collections/4 27 Using the Sieve import ds.util.Bag; public class UseSieve { public static void main(String[] args) { Bag bag = sieve(500); Object[] arr = bag.toArray(); Arrays.sort(arr); writePrimes(arr); } Display all primes from 2 to 500.
28
ADSA: Collections/4 28 public static Bag sieve(int n) { Bag primeBag = new Bag (n); // fill the set with integers 2, 3,..., n for (int m = 2; m <= n; m++) primeBag.add( new Integer(m) ); :
29
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 <
30
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()); :
31
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
32
ADSA: Collections/4 32 Execution 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499
33
ADSA: Collections/4 33 5. Implementing the Bag Class public class Bag implements Collection { 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.
34
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 }
35
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--; }
36
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
37
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 later
38
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 continued
39
ADSA: Collections/4 39 continued
40
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 continued
41
ADSA: Collections/4 41 Create a collection: // create a linked list of integers LinkedList aList =...; Create an iterator() for the collection that you want to scan: Iterator iter = aList.iterator(); Collection.iterator() is called a factory method –a non-constructor method that creates objects
42
ADSA: Collections/4 42 Iterator Methods Iterator.hasNext() indicates whether more values remain in a collection scan. // continue while there are remaining elements while (iter.hasNext()) {... } Ford & Topp's iter arrows are misleading; I've changed them. later...
43
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 continued
44
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 } continued
45
ADSA: Collections/4 45 The Iterator method remove() applied after a call to next() removes the collection value that was previously returned by next().
46
ADSA: Collections/4 46 Iterator Interface API
47
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.
48
ADSA: Collections/4 48 max() public static T max (Collection c) { // create an iterator positioned at list start Iterator 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; }
49
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.
50
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
51
ADSA: Collections/4 51 Set, List, and Queue Interfaces
52
ADSA: Collections/4 52 List in more Detail (JDK 6)
53
ADSA: Collections/4 53 Set in more Detail (JDK 6) NavigableSet: a set with navigation methods
54
ADSA: Collections/4 54 Queue in more Detail (JDK 6) deque (deck): insert/remove at both ends
55
ADSA: Collections/4 55 The Map Interface Use the Map interface to store 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
56
ADSA: Collections/4 56 Map in Detail (JDK 6)
57
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.
58
ADSA: Collections/4 58 List in Full Also Vector (but old fashioned)
59
ADSA: Collections/4 59 Set in Full
60
ADSA: Collections/4 60 Queue in Full (very full) BlockingQueue: v.useful for message passing between threads
61
ADSA: Collections/4 61 Map in Full Also Hashtable (but old fashioned)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.