• Tidak ada hasil yang ditemukan

PPT Slide 1

N/A
N/A
Protected

Academic year: 2023

Membagikan "PPT Slide 1"

Copied!
36
0
0

Teks penuh

(1)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Data Structures for Java Data Structures for Java

William H. Ford William H. Ford William R. Topp William R. Topp

Chapter 8 Chapter 8

Collection Types Collection Types

Bret Ford

© 2005, Prentice Hall

(2)

Collection Collection

 A collection is an object that holds other A collection is an object that holds other objects. It is a storage mechanism with objects. It is a storage mechanism with

operations for adding and removing operations for adding and removing

elements and for accessing and perhaps elements and for accessing and perhaps

updating their values.

updating their values.

(3)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Collection Interface Collection Interface

The generic Collection interface defines a set The generic Collection interface defines a set of operations that characterize the behavior of operations that characterize the behavior

of most collection classes.

of most collection classes.

(4)

Collection Interface Collection Interface

(continued)

(continued)

(5)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Collection Interface Collection Interface

(concluded)

(concluded)

(6)

List Collection 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. 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.

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 ArrayList Collection

An ArrayList collection is a generalized array that An ArrayList collection is a generalized array that sores element in a contiguous block of memory.

sores element in a contiguous block of memory.

The collection is dynamic in that it automatically The collection is dynamic in that it automatically

expands to handle insert of new elements.

expands to handle insert of new elements.

An ArrayList is a direct-access structure An ArrayList is a direct-access structure

(8)

ArrayList Collection ArrayList Collection

(concluded) (concluded)

The collection efficiently (O(1)) inserts and The collection efficiently (O(1)) inserts and deletes elements at the rear of the list. The deletes elements at the rear of the list. The

operations at intermediate positions have O(n) operations at intermediate positions have O(n)

efficiency since the tail of the list must be shifted efficiency since the tail of the list must be shifted

right (insertion) or left (deletion).

right (insertion) or left (deletion).

(9)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

LinkedList Collection LinkedList Collection

A LinkedList collection is a sequence whose A LinkedList collection is a sequence whose elements have a value and links that identify elements have a value and links that identify

adjacent elements in the sequence.

adjacent elements in the sequence.

A LinkedList is a sequential- access structure. A LinkedList is a sequential- access structure.

(10)

LinkedList Collection LinkedList Collection

(concluded) (concluded)

Inserting or deleting elements in a LinkedList Inserting or deleting elements in a LinkedList involves altering the links that connect the involves altering the links that connect the

elements in the list. These are O(1) operations.

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 Set Collection

A Bag is a general collection class that implements the Collection interface. A 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

Set is a collection that resembles a Bag with the provision that duplicate values are not allowed.

values are not allowed.

Applications typically use Set collections for operations set union, set Applications typically use Set collections for operations set union, set intersection, and set difference.

intersection, and set difference.

(12)

Map Collection Map Collection

A Map is a collection of key-value pairs. The key A Map is a collection of key-value pairs. The key uniquely identifies the element while the value field uniquely identifies the element while the value field typically has associated data. Access to an element typically has associated data. Access to an element

requires only the key and returns the value requires only the key and returns the value

component. For this reason, a Map is referred to component. For this reason, a Map is referred to

as an associative array.

as an associative array.

(13)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Stack Collection Stack Collection

A Stack is a collection with a single reference point A Stack is a collection with a single reference point called the top of the stack. An element is added at called the top of the stack. An element is added at the top of the stack (push operation) and removed the top of the stack (push operation) and removed

from the top of the stack (pop operation).

from the top of the stack (pop operation).

Elements come off a stack in the reverse order of Elements come off a stack in the reverse order of their insertion and so a stack has last-in-first-out their insertion and so a stack has last-in-first-out

(LIFO) ordering.

(LIFO) ordering.

(14)

Queue Collection Queue Collection

A Queue is a collection that allows access only at A Queue is a collection that allows access only at the front and the back. Items enter at the back the front and the back. Items enter at the back

(push operation) and exit from the front of the (push operation) and exit from the front of the

queue (pop operation).

queue (pop operation).

Elements come off a queue in the same order of Elements come off a queue in the same order of their insertion and so a queue has first-in-first- their insertion and so a queue has first-in-first-

out (FIFO) ordering.

out (FIFO) ordering.

(15)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Priority Queue Priority Queue

A Priority Queue is a collection that has restricted A Priority Queue is a collection that has restricted access operations, like a stack and a queue. An access operations, like a stack and a queue. An

element can enter the queue in any order. Once element can enter the queue in any order. Once in the collection, a delete operation removes the in the collection, a delete operation removes the

maximum (minimum) value, depending on the maximum (minimum) value, depending on the

specified type of priority.

specified type of priority.

(16)

Graph Collection Graph Collection

A Graph is a set of vertices connected by links, A Graph is a set of vertices connected by links, called edges. Depending on the application, an called edges. Depending on the application, an edge may or may not have a direction and/or a edge may or may not have a direction and/or a

weight. A digraph has directed edges; a weight. A digraph has directed edges; a weighted graph has edges with weights.

weighted graph has edges with weights.

(17)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Java Collection Framework Java Collection Framework

The Java Collection Framework is a group of The Java Collection Framework is a group of collections defined using interfaces abstract collections defined using interfaces abstract

classes, and inheritance.

classes, and inheritance.

(18)

Bag Collection Bag Collection

 The Bag class is a generic collection that The Bag class is a generic collection that implements the Collection interface.

implements the Collection interface.

Duplicate values are allowed.

Duplicate values are allowed.

 In the Bag class, the method grab() In the Bag class, the method grab() returns a random element in the

returns a random element in the

collection. The method toString() returns collection. The method toString() returns

a comma-separated list of elements

a comma-separated list of elements

(19)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 8.1 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<Character> 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)

Program 8.1 (continued) 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<Character>(str.length());

bagB = new Bag<Character>(str.length());

(21)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 8.1 (continued) 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)

Program 8.1 (concluded) 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));

} }

(23)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Sieve of Eratosthenes Sieve of Eratosthenes

The Sieve of Eratosthenes uses a bag to find all The Sieve of Eratosthenes uses a bag to find all primes less than or equal to an integer value n.

primes less than or equal to an integer value n.

Begin by creating a bag an inserting values from Begin by creating a bag an inserting values from

2 to n. Using values 2, 3, 4, and so forth, remove 2 to n. Using values 2, 3, 4, and so forth, remove

all multiple, leaving only the prime numbers.

all multiple, leaving only the prime numbers.

E.g. The figure illustrates the sieve of E.g. The figure illustrates the sieve of

Eratosthenes when finding all prime numbers in Eratosthenes when finding all prime numbers in

the range from 2 through 25.

the range from 2 through 25.

(24)

The method sieve(n) The method sieve(n)

public static Bag<Integer> sieve(int n) {

int m, i;

Bag<Integer> primeBag = new Bag<Integer>(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))

(25)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

sieve(n) (concluded) 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)

Program 8.2 Program 8.2

import ds.util.Bag;

public class Program8_2 {

public static void main(String[] args) {

final int PRIMELIMIT = 500;

Bag<Integer> bag;

// call sieve() and return the bag of primes bag = sieve(PRIMELIMIT);

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) 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)

Program 8.2 (concluded) Program 8.2 (concluded)

// every 10 elements output a newline if(count % 10 == 0)

System.out.println();

count++;

} }

< sieve() developed in the preliminary discussion >

}

(29)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 8.2 (Run) 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)

Implementing the Bag Class Implementing the Bag Class

public class Bag<T> implements Collection<T>

{

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 Implementing the Bag Class

(concluded) (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)

Private remove(int i) Method 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 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)

add(item) Method 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++;

(35)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

grab() Method 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)

toString() Method toString() Method

public String toString() {

// array is copy of elements Object[] arr = toArray();

// listing of elements

return Arrays.toString(arr);

}

Gambar

Graph CollectionGraph Collection

Referensi

Dokumen terkait

Lancet Public Health 2018; 3: e365–73—In this Article, the labels for the cumulative individual socioeconomic disadvantage category in table 1 were in the wrong order.. The labels in