370 likes | 1.25k Views
14.2 – Let’s play Bingo. Rules Each player has a random card like 5 groups of numbers correspond to each of 5 letters: B: 1-15; I: 16-30; N:31-45; G:46-60; O:61-75 Caller pulls balls numbered 1-75 randomly from a bag .
E N D
14.2 – Let’s play Bingo • Rules • Each player has a random card like • 5 groups of numbers correspond to each of 5 letters: • B: 1-15; I: 16-30; N:31-45; G:46-60; O:61-75 • Caller pulls balls numbered 1-75 randomly from a bag. • The first person who completes “BINGO” in any straight direction, wins • How do you implement it?
14.2 – BingoBall.java //******************************************************************** // Represents a ball used in a Bingo game. //******************************************************************** public class BingoBall { private char letter; private int number; //----------------------------------------------------------------- // Constructs a Bingo ball with specified number and appropriate letter. //----------------------------------------------------------------- public BingoBall (int num) { number = num; if (num <= 15) letter = 'B'; else if (num <= 30) letter = 'I'; else if (num <= 45) letter = 'N'; else if (num <= 60) letter = 'G'; else letter = 'O'; } (etc.) }
14.2 – A Bag Collection • A bag is a collection that facilitates the selection of random elements from the group • A bag is nonlinear; elements in the bag have no particular positional relationship to each other • The implementation of the bag will store the elements in an array or using some other technique
14.1 –Collections • A collectionis an object that serves as a repository for other objects • A collection provides services to add, remove, and manage the elements it contains • The underlying data structure used to implement the collection is independent of the operations provided • Collections can be separated into two categories • linear: elements are organized in a straight line • nonlinear: elements are organized in something other than a straight line • Ordering of elements, relative to each other, is usually determined by either • the order in which they were added to the collection • or some inherent relationship among the elements
14.1 – Collection: Your First ADT • An abstract data type (ADT) is a set of data and the particular operations that are allowed on that data • “Abstract” because the operations you can perform on it are separated from the underlying implementation • A collection is an ADT • For every collection we examine, we should consider • How does the collection operate, conceptually? • What operations are included in the interface to the collection? • What kinds of problems does the collection help us solve? • How might the collection be implemented? • How do the implementations compare from an efficiency point of view?
Class thatimplementsthe collection Services provided by collection that adhere to an interface Separating Interface from Implementation Interface to collection Class that usesthe collection
14.2 – javafoundations.Bag //******************************************************************* // Bag.java Java Foundations // Defines the interface to a bag collection. //******************************************************************* package javafoundations; public interface Bag<T> extends Iterable<T> { // Adds the specified element to the bag. public void add (T element); // Removes and returns a random element from the bag. public T remove(); // Returns true if bag contains no elements, false otherwise. public boolean isEmpty(); // Returns the number of elements in the bag. public int size(); // Returns a string representation of the bag. public String toString(); }
14.1 – On Generic Types <T> • Our defined class will then be able to store, operate on, and manage objects whose type is not specified until the class is instantiated • Example: define a Group class that stores and manages a group of objects. • We can define Group to store references to the Object class(allowed by polymorphism) • However, any type of object could then be stored in our Group, resulting in a loss of control • A better approach is to define the Group to store a generic type T class Group<T> { // declarations and code that manages objects of type T }
14.1 – Generic Types • Instantiating a Group of Product objects Group<Product> group1 = new Group<Product>; • Instantiating a Group of Friend objects Group<Friend> group2 = new Group<Friend>; • A generic type Tcan not be instantiated • Sometimes we want our stored items to be Comparable class Group<T extends Comparable<T>> { // declarations and code that manages objects of type T }
14.2 – Back to our Bingo Game • A bag collection is perfectly suited to support a Bingo game • The collection will hold BingoBall objects and will use an array as the basis of the implementation • Our collection will be known as an ArrayBag
The UML diagram of the interactions <<interface>>Iterable <<interface>>Iterator public interface Bag<T> extends Iterable<T> In such a simple program we do not really need Iterable, but is a nice excuse to study a more complex interaction between interfaces and implementations <<interface>> Bag ArrayIterator ArrayBag Bingo BingoBall
//********************************************************************//******************************************************************** // Bingo.java Java Foundations // Demonstrates the use of a bag collection. //******************************************************************** import javafoundations.ArrayBag; public class Bingo { //----------------------------------------------------------------- // Creates all 75 Bingo balls and stores them in a bag. Then // pulls several balls from the bag at random and prints them. //----------------------------------------------------------------- public static void main (String[] args) { final int NUM_BALLS = 75, NUM_PULLS = 20; ArrayBag<BingoBall> bingoBag = new ArrayBag<BingoBall>(); BingoBall ball; for (int num = 1; num <= NUM_BALLS; num++) bingoBag.add (new BingoBall(num)); System.out.println ("Size: " + bingoBag.size() + "\n"); for (int num = 1; num <= NUM_PULLS; num++) { ball = bingoBag.remove(); System.out.println (ball); } } } 14.2 – Bingo.java
Changing the CLASSPATH Because we import javafoundations.ArrayBag; we need to tell Java where to find this package: HD:~ tm$ echo $CLASSPATH . HD:~ tm$ CLASSPATH=/Users/tm/:. HD:~ tm$ export CLASSPATH HD:~ tm$ echo $CLASSPATH /Users/tm/:. Or we can compile and run with the full path: HD:~ tm$ javac -cp /Users/tm/:. Bingo.java HD:~ tm$ java -cp /Users/tm/:. Bingo Or we can tell Dr. Java where to find it
14.3 – An Array Implementation of a Bag • We could use Java’s SDK to implement Bingo • Or we could use the library provided by the book authors • Let’s develop ArrayBag (in javafoundations package) • Issues: • An array can be used to store the elements of our collection • However, an array has a fixed size once it is created • Collections sometimes are limited to a specific size • We don’t wish to have our bag limited by this constraint • When the bag is “full” we want to support reallocating space for the array to “grow” the collection
14.3 – javafoundations.ArrayBag //******************************************************************** // ArrayBag.java Java Foundations // // Represents an array implementation of bag collection. //******************************************************************** package javafoundations; import java.util.*; import javafoundations.exceptions.EmptyCollectionException; public class ArrayBag<T> implements Bag<T> { private final int DEFAULT_CAPACITY = 10; private int count; private T[] contents; private static Random rand = new Random(); (more…)
//----------------------------------------------------------------- // Creates an empty bag using the default capacity. //----------------------------------------------------------------- public ArrayBag() { count = 0; contents = (T[]) (new Object[DEFAULT_CAPACITY]); } //----------------------------------------------------------------- // Adds the specified element to this bag by storing the element // at the end of the list, expanding the array capacity if needed. //----------------------------------------------------------------- public void add (T element) { if (count == contents.length) expandCapacity(); // insert your code here to add element: } (more…) 14.3 – javafoundations.ArrayBag
//----------------------------------------------------------------- // Removes a random element from this bag, shifting the last // element into its place to keep the list contiguous. Throws // EmptyCollectionException if this bag is empty. //----------------------------------------------------------------- public T remove() throws EmptyCollectionException { if (count == 0) throw new EmptyCollectionException ("Remove operation " + "failed. The bag is empty."); int index = rand.nextInt(count); T result = contents[index]; // insert your code here to remove the element at location index: return result; } (more…) 14.3 – javafoundations.ArrayBag
//----------------------------------------------------------------- // Returns true if this bag contains no elements, and false // otherwise. //----------------------------------------------------------------- public boolean isEmpty() { // insert your code here } //----------------------------------------------------------------- // Returns the number of elements in this bag. //----------------------------------------------------------------- public int size() { // insert your code here } (more…) 14.3 – javafoundations.ArrayBag
//----------------------------------------------------------------- // Creates a new array to store the contents of this bag with // twice the capacity of the old one. //----------------------------------------------------------------- private void expandCapacity() { T[] larger = (T []) (new Object[contents.length*2]); int location = 0; for (T element : contents) larger[location++] = element; contents = larger; } //----------------------------------------------------------------- // Returns a string representation of this bag. //----------------------------------------------------------------- public String toString() { String result = "Bag Contents:\n”; for (int index=0; index < count; index++) result += contents[index] + "\n”; return result; } (more…) 14.3 – javafoundations.ArrayBag
We are not done yet! (public interface Bag<T> extends Iterable<T>) //----------------------------------------------------------------- // Returns an iterator for this bag. //----------------------------------------------------------------- public Iterator<T> iterator() { ArrayIterator<T> iter = new ArrayIterator<T>(); for (int index = 0; index < count; index++) iter.add(contents[index]); return iter; } }
14.3 – Remember “Iterable”? • public interface Bag<T> extends Iterable<T> • The Iterable interface contains only: Iterator<T> iterator(); • So we need to implement Iterator • The ArrayIterator implements the Iteratorinterface, => we must include the hasNext, next, and removemethods • The class is so named because it uses an array as the underlying structure to hold the elements in the iterator • It’s generally not a good idea to remove an element from a collection using an iterator • Another advantage to of making a collection Iterableis that then it can be processed using the for-eachloop
//********************************************************************//******************************************************************** // ArrayIterator.java Java Foundations // Represents an iterator over the elements of a collection. //******************************************************************** package javafoundations; import java.util.*; public class ArrayIterator<T> implements Iterator<T> { private int DEFAULT_CAPACITY = 10; private int count; // the number of elements in the iterator private int current; // the current position in the iteration private T[] items; // the iterator's storage for elements //----------------------------------------------------------------- // Sets up this iterator. //----------------------------------------------------------------- public ArrayIterator() { items = (T[]) (new Object[DEFAULT_CAPACITY]); count = 0; current = 0; } (more…) 14.3 – javafoundations.ArrayIterator
//----------------------------------------------------------------- // Adds the specified item to this iterator. //----------------------------------------------------------------- public void add (T item) { if (count == items.length) expandCapacity(); items[count] = item; count++; } //----------------------------------------------------------------- // Returns true if this iterator has at least one more element to // deliver in the iteration. //----------------------------------------------------------------- public boolean hasNext() { return (current < count); } (more…)
//----------------------------------------------------------------- // Returns the next element in the iteration. If there are no more // elements in this iteration, a NoSuchElementException is thrown. //----------------------------------------------------------------- public T next() { if (! hasNext()) throw new NoSuchElementException(); current++; return items[current - 1]; } //----------------------------------------------------------------- // The remove operation is not supported in this collection. //----------------------------------------------------------------- public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } (more…)
14.3 – javafoundations.ArrayIterator //----------------------------------------------------------------- // Exapands the capacity of the storage array //----------------------------------------------------------------- private void expandCapacity() { T[] larger = (T []) (new Object[items.length*2]); int location = 0; for (T element : items) larger[location++] = element; items = larger; } }