Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection Types Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Collection A collection is an object that holds other objects. It is a storage mechanism with operations for adding and removing elements and for accessing and perhaps updating their values. A collection is an object that holds other objects. It is a storage mechanism with operations for adding and removing elements and for accessing and perhaps updating their values.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Collection Interface The generic Collection interface defines a set of operations that characterize the behavior of most collection classes. The generic Collection interface defines a set of operations that characterize the behavior of most collection classes.

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Collection Interface (continued)

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Collection Interface (concluded)

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. List Collection A List collection stores elements by position and includes index-based operations. A List collection stores elements by position and includes index-based operations. 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. 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.

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. ArrayList Collection An ArrayList collection is a generalized array that sores element in a contiguous block of memory. The collection is dynamic in that it automatically expands to handle insert of new elements. An ArrayList collection is a generalized array that sores element in a contiguous block of memory. The collection is dynamic in that it automatically expands to handle insert of new elements. An ArrayList is a direct-access structure An ArrayList is a direct-access structure

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. ArrayList Collection (concluded) The collection efficiently (O(1)) inserts and deletes elements at the rear of the list. The operations at intermediate positions have O(n) efficiency since the tail of the list must be shifted right (insertion) or left (deletion). The collection efficiently (O(1)) inserts and deletes elements at the rear of the list. The operations at intermediate positions have O(n) efficiency since the tail of the list must be shifted right (insertion) or left (deletion).

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. LinkedList Collection A LinkedList collection is a sequence whose elements have a value and links that identify adjacent elements in the sequence. A LinkedList collection is a sequence whose elements have a value and links that identify adjacent elements in the sequence. A LinkedList is a sequential- access structure. A LinkedList is a sequential- access structure.

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. LinkedList Collection (concluded) Inserting or deleting elements in a LinkedList involves altering the links that connect the elements in the list. These are O(1) operations. Inserting or deleting elements in a LinkedList involves altering the links that connect the elements in the list. These are O(1) operations. A Linked List class can be extended to the OrderedList class that creates collections that store elements in order.

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Set Collection A Bag is a general collection class that implements the Collection interface. A Set is a collection that resembles a Bag with the provision that duplicate values are not allowed. A Bag is a general collection class that implements the Collection interface. A Set is a collection that resembles a Bag with the provision that duplicate values are not allowed. Applications typically use Set collections for operations set union, set intersection, and set difference.

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Map Collection A Map is a collection of key-value pairs. The key uniquely identifies the element while the value field typically has associated data. Access to an element requires only the key and returns the value component. For this reason, a Map is referred to as an associative array. A Map is a collection of key-value pairs. The key uniquely identifies the element while the value field typically has associated data. Access to an element requires only the key and returns the value component. For this reason, a Map is referred to as an associative array.

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Stack Collection A Stack is a collection with a single reference point called the top of the stack. An element is added at the top of the stack (push operation) and removed from the top of the stack (pop operation). A Stack is a collection with a single reference point called the top of the stack. An element is added at the top of the stack (push operation) and removed from the top of the stack (pop operation). Elements come off a stack in the reverse order of their insertion and so a stack has last-in-first-out (LIFO) ordering. Elements come off a stack in the reverse order of their insertion and so a stack has last-in-first-out (LIFO) ordering.

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Queue Collection A Queue is a collection that allows access only at the front and the back. Items enter at the back (push operation) and exit from the front of the queue (pop operation). A Queue is a collection that allows access only at the front and the back. Items enter at the back (push operation) and exit from the front of the queue (pop operation). Elements come off a queue in the same order of their insertion and so a queue has first-in-first- out (FIFO) ordering. Elements come off a queue in the same order of their insertion and so a queue has first-in-first- out (FIFO) ordering.

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Priority Queue A Priority Queue is a collection that has restricted access operations, like a stack and a queue. An element can enter the queue in any order. Once in the collection, a delete operation removes the maximum (minimum) value, depending on the specified type of priority. A Priority Queue is a collection that has restricted access operations, like a stack and a queue. An element can enter the queue in any order. Once in the collection, a delete operation removes the maximum (minimum) value, depending on the specified type of priority.

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Graph Collection A Graph is a set of vertices connected by links, called edges. Depending on the application, an edge may or may not have a direction and/or a weight. A digraph has directed edges; a weighted graph has edges with weights. A Graph is a set of vertices connected by links, called edges. Depending on the application, an edge may or may not have a direction and/or a weight. A digraph has directed edges; a weighted graph has edges with weights.

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Java Collection Framework The Java Collection Framework is a group of collections defined using interfaces abstract classes, and inheritance. The Java Collection Framework is a group of collections defined using interfaces abstract classes, and inheritance.

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Bag Collection The Bag class is a generic collection that implements the Collection interface. Duplicate values are allowed. The Bag class is a generic collection that implements the Collection interface. Duplicate values are allowed. In the Bag class, the method grab() returns a random element in the collection. The method toString() returns a comma-separated list of elements enclosed in brackets. In the Bag class, the method grab() returns a random element in the collection. The method toString() returns a comma-separated list of elements enclosed in brackets.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.1 import ds.util.Bag; import ds.util.Arrays; import java.util.Scanner; public class Program8_1 { public static void main(String[] args) { // keyboard input stream and input string Scanner keyIn = new Scanner(System.in); String str = ""; // Bag objects hold string characters Bag bagA, bagB; The program uses Bag collections to identify distinct elements in a string and displays them in an ordered list. Input of the string comes from the keyboard.

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.1 (continued) // Character object for char // in the input string Character ch; // flag used to remove duplicates from bagA boolean foundDuplicate; // prompt for input string System.out.print("Enter a string: "); str = keyIn.next(); // create the collections with // capacity str.length() bagA = new Bag (str.length()); bagB = new Bag (str.length()); // add characters from the string to bagA for (int i = 0; i < str.length(); i++) bagA.add(str.charAt(i));

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.1 (continued) // use grab() to fetch a character from // bagA; add it to bagB and then remove // all occurrences of the character // from bagA; continue this process until // bagA is empty while (!bagA.isEmpty()) { // remove a random character from bagA // and add to bagB ch = bagA.grab(); bagB.add(ch); // remove all occurrence of // target = chObj from bagA do foundDuplicate = bagA.remove(ch); while (foundDuplicate); }

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.1 (concluded) // create array of Object references // corresponding to elements in bagB; sort // array and output its values using static // methods sort() and toString(arr) Object[] objArr = bagB.toArray(); Arrays.sort(objArr); System.out.println("Sorted letters: " + Arrays.toString(objArr)); } Run: Enter a string: mississippi Sorted letters: [i, m, p, s]

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Sieve of Eratosthenes The Sieve of Eratosthenes uses a bag to find all primes less than or equal to an integer value n. Begin by creating a bag an inserting values from 2 to n. Using values 2, 3, 4, and so forth, remove all multiple, leaving only the prime numbers. E.g. The figure illustrates the sieve of Eratosthenes when finding all prime numbers in the range from 2 through 25. The Sieve of Eratosthenes uses a bag to find all primes less than or equal to an integer value n. Begin by creating a bag an inserting values from 2 to n. Using values 2, 3, 4, and so forth, remove all multiple, leaving only the prime numbers. E.g. The figure illustrates the sieve of Eratosthenes when finding all prime numbers in the range from 2 through 25.

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The method sieve(n) public static Bag sieve(int n) { int m, i; Bag primeBag = new Bag (n); // load the set with integers 2, 3,..., n for (m = 2; m <= n; m++) primeBag.add(new Integer(m)); // find the primes using the Sieve of Eratosthenes; // look at numbers from // m = 2 to m * m > n (m <= sqrt(n)) for (m = 2; m * m <= n; m++)

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. sieve(n) (concluded) // check if m is still in the set; if so // remove all multiples of m starting with 2*m if(primeBag.contains(new Integer(m))) { // i sequences through successive multiples of m, // 2*m, 3*m,... i = 2 * m; while (i <= n) { primeBag.remove(new Integer(i)); // update i to the next multiple of m i += m; } return primeBag; }

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.2 import ds.util.Bag; public class Program8_2 { public static void main(String[] args) { final int PRIMELIMIT = 500; Bag bag; // call sieve() and return the bag of primes bag = sieve(PRIMELIMIT); // list elements in the bag as an array // output primes in 6 spaces, 10 per line writePrimes(bag.toArray()); System.out.println(); } The program uses the Sieve of Eratosthenes to display all primes from 2 to PRIMELIMIT = 500.

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.2 (continued) // output elements in the array // in 6 spaces, 10 per line public static void writePrimes(Object[] arr) { String intStr; int count = 1, i; // initialize sb with 6 blanks StringBuffer sb = new StringBuffer(" "); for (i = 0; i < arr.length; i++) { // convert integer to a string intStr = arr[i].toString(); // use replace() to place intStr // in the string buffer. sb.replace(0, intStr.length(), intStr); // output string buffer as a string System.out.print(sb.toString());

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.2 (concluded) // every 10 elements output a newline if(count % 10 == 0) System.out.println(); count++; } }

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 8.2 (Run) Run: 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

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the Bag Class public class Bag implements Collection { private T[] bagArr; // storage structure private int bagSize; // size of collection // used by grab() private static Random rnd = new Random(); // private methods used by the public methods... The Bag class uses a fixed-size array as the storage structure. The size of the array is dependent on a constructor argument.

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the Bag Class (concluded) // constructor creates an empty collection // with fixed capacity public Bag(int capacity) { // value of capacity is maximum number of elements bagArr = (T[])new Object[capacity]; bagSize = 0; } // interface methods and the grab() method... }

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Private remove(int i) Method // remove the element bagArr[i] by moving the tail of // the array left one position and decrementing bagSize private void remove(int i) { // copy bagArr[i+1]... bagArr[bagSize-1] // left one position for (int j=i; j < bagSize-1; j++) bagArr[j] = bagArr[j+1]; // decrement bagSize bagSize--; }

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. General remove(item) Method public boolean remove(Object item) { // scan for item using equals() as the test for (int i=0;i < bagSize;i++) if (bagArr[i].equals(item)) { // call private remove method to delete bagArr[i] remove(i); return true; } return false; }

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. add(item) Method public boolean add(T item) { boolean returnValue; if (bagSize >= bagArr.length) return false; else { // append item at index bagSize bagArr[bagSize] = item; // increment bagSize and return true bagSize++; return true; }

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. grab() Method // return value of random object in range (0,bagSize) public T grab() { if (bagSize == 0) return null; else return bagArr[rnd.nextInt(bagSize)]; }

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. toString() Method public String toString() { // array is copy of elements Object[] arr = toArray(); // listing of elements return Arrays.toString(arr); }


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection."

Similar presentations


Ads by Google