Professional Documents
Culture Documents
Topic 2: Bags
Hao Ji
Computer Science Department
Cal Poly Pomona
© 2018 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The ADT Bag
• Definition
• A finite collection of objects in no particular order
• Can contain duplicate items
Bag
• Possible behaviors
• Get number of items
• Check for empty
• Add and remove objects
2
Using UML Notation to Specify a Class
<<interface>>
Bag
3
/** An interface that describes the operations of a bag of objects. */
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag, if possible.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to find.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag. Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
4
} // end BagInterface
/** A class that maintains a shopping cart for an online store. */ public class Item
public class OnlineShopper {
{ private String description;
public static void main(String[] args) private int price;
{
Item[] items = {new Item("Bird feeder", 2050),
new Item("Squirrel guard", 1547), public Item(String productDescription, int productPrice)
new Item("Bird bath", 4499), {
new Item("Sunflower seeds", 1295)}; description = productDescription;
price = productPrice;
BagInterface<Item> shoppingCart = new ArrayBag<>(); } // end constructor
int totalCost = 0;
public String getDescription()
// Statements that add selected items to the shopping cart: {
for (int index = 0; index < items.length; index++)
{ return description;
Item nextItem = items[index]; // Simulate getting item from shopper } // end getDescription
shoppingCart.add(nextItem);
totalCost = totalCost + nextItem.getPrice(); public int getPrice()
} // end for {
return price;
// Simulate checkout } // end getPrice
while (!shoppingCart.isEmpty())
System.out.println(shoppingCart.remove()); public String toString()
System.out.println("Total cost: " + "\t$" + totalCost / 100 + "." + totalCost % 100); {
} // end main return description + "\t$" + price / 100 + "." + price % 100;
} // end OnlineShopper } // end toString
} // end Item
5
Implementations of a Bag
6
Implementations of a Bag
• Using Fixed-Size Arrays
• Using Array Resizing
• Using Linked Data
7
Implementations of a Bag
• Using Fixed-Size Arrays
ArrayBag
• Using Array Resizing -bag: T[]
• Using Linked Data -numberOfEntries: integer
-DEFAULT_CAPACITY: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean
8
Bag Implementations That Use Arrays
• Private Data Fields
9
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
10
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
• Option 1:
• Option 2:
• Option 3:
• Option 4:
11
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
• Option 1:
You cannot use a generic type when allocating an array
12
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
• Option 1:
• Option 2:
You cannot assign an array of type Object[] to an array of type T[].
13
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
• Option 1:
• Option 2:
• Option 3: // warning: ArrayBag.java uses unchecked or unsafe operations.
You can instruct the compiler to ignore the warning by writing the annotation
@SuppressWarnings("unchecked") before the offending statement
14
Bag Implementations That Use Arrays
• Constructors
• Initialize the field numberOfEntries to 0.
• Create the array bag.
• To create the array, the constructor must
specify the array’s length, which is the
bag’s capacity.
• Option 1:
• Option 2:
• Option 3: // warning: ArrayBag.java uses unchecked or unsafe operations.
• Option 4: // This instruction to the compiler can only precede a method definition
or a variable declaration.
15
Bag Implementations That Use Arrays
• The method add
• If the bag is full, we cannot add anything to it.
In that case, the method add should return
false
• Otherwise, we simply add newEntry
immediately after the last entry in the array
bag
16
Bag Implementations That Use Arrays
• The method add
• If the bag is full, we cannot add anything to it.
In that case, the method add should return
false
• Otherwise, we simply add newEntry
immediately after the last entry in the array
bag
17
Bag Implementations That Use Arrays
• The method add
• If the bag is full, we cannot add anything to it.
In that case, the method add should return
false
• Otherwise, we simply add newEntry
immediately after the last entry in the array
bag
18
Bag Implementations That Use Arrays
• The method toArray
• Retrieves the entries that are in a bag
• Returns them to the client within a newly
allocated array.
19
Bag Implementations That Use Arrays
• The method toArray
• Retrieves the entries that are in a bag
• Returns them to the client within a newly
allocated array.
20
Bag Implementations That Use Arrays
• The method toArray
• Retrieves the entries that are in a bag
• Returns them to the client within a newly
allocated array.
21
Bag Implementations That Use Arrays
• The method toArray
• Retrieves the entries that are in a bag
• Returns them to the client within a newly
allocated array.
22
Bag Implementations That Use Arrays
• The method isFull()
• A bag is full when it contains as many objects
as the array bag can accommodate.
23
Bag Implementations That Use Arrays
• The method isFull()
• A bag is full when it contains as many objects
as the array bag can accommodate.
24
A Test Program
25
Making the Implementation Secure
• Practice fail-safe programming by including checks for anticipated errors
• Validate input data and arguments to a method
• Refine incomplete implementation of ArrayBag to make code more secure by
adding the following two data fields:
private boolean integrityOK = false;
private static final int MAX_CAPACITY = 10000;
26
Making the Implementation Secure
ArrayBag
• Revised Constructor -bag: T[]
/** Creates an empty bag having a given capacity. -numberOfEntries: integer
@param desiredCapacity The integer capacity desired. */ -DEFAULT_CAPACITY: integer
public ArrayBag(int desiredCapacity)
{
-integrityOK: Boolean
if (desiredCapacity <= MAX_CAPACITY) -MAX_CAPACITY: integer
{ +getCurrentSize(): integer
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked") +isEmpty(): boolean
T[] tempBag = (T[])new Object[desiredCapacity]; // Unchecked cast +add(newEntry: T): boolean
bag = tempBag;
numberOfEntries = 0; +remove(): T
integrityOK = true; +remove(anEntry: T): boolean
}
else +clear(): void
throw new IllegalStateException("Attempt to create a bag whose" +getFrequencyOf(anEntry: T): integer
+ "capacity exceeds allowed maximum.");
} // end constructor
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 27
Making the Implementation Secure
ArrayBag
• Method to check initialization -bag: T[]
// Throws an exception if this object is not initialized. -numberOfEntries: integer
private void checkIntegrity() -DEFAULT_CAPACITY: integer
{
if (!integrityOK) -integrityOK: Boolean
throw new SecurityException("ArrayBag object is corrupt."); -MAX_CAPACITY: integer
} // end checkIntegrity
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 28
Making the Implementation Secure
ArrayBag
• Revised method add -bag: T[]
-numberOfEntries: integer
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry. -DEFAULT_CAPACITY: integer
@return True if the addition is successful, or false if not. */ -integrityOK: Boolean
public boolean add(T newEntry)
{ -MAX_CAPACITY: integer
checkIntegrity(); +getCurrentSize(): integer
boolean result = true;
if (isArrayFull())
+isEmpty(): boolean
{ +add(newEntry: T): boolean
result = false;
+remove(): T
}
else +remove(anEntry: T): boolean
{ // Assertion: result is true here +clear(): void
bag[numberOfEntries] = newEntry;
numberOfEntries++; +getFrequencyOf(anEntry: T): integer
} // end if +contains(anEntry: T): boolean
return result; +toArray(): T[]
} // end add –isArrayFull(): boolean 29
Implementing More Methods
ArrayBag
-bag: T[]
-numberOfEntries: integer
-DEFAULT_CAPACITY: integer
-integrityOK: Boolean
-MAX_CAPACITY: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 30
Implementing More Methods
ArrayBag
/** Sees whether this bag is empty.
@return True if this bag is empty, or false if not. */
-bag: T[]
public boolean isEmpty() -numberOfEntries: integer
{
return numberOfEntries == 0;
-DEFAULT_CAPACITY: integer
} // end isEmpty -integrityOK: Boolean
-MAX_CAPACITY: integer
/** Gets the current number of entries in this bag. +getCurrentSize(): integer
@return The integer number of entries currently in this bag. */ +isEmpty(): boolean
public int getCurrentSize()
{ +add(newEntry: T): boolean
return numberOfEntries; +remove(): T
} // end getCurrentSize
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 31
Implementing More Methods
ArrayBag
-bag: T[]
-numberOfEntries: integer
/** Counts the number of times a given entry appears in this bag. -DEFAULT_CAPACITY: integer
@param anEntry The entry to be counted.
@return The number of times anEntry appears in this bag. */ -integrityOK: Boolean
public int getFrequencyOf(T anEntry) -MAX_CAPACITY: integer
{
checkIntegrity(); +getCurrentSize(): integer
int counter = 0; +isEmpty(): boolean
for (int index = 0; index < numberOfEntries; index++)
+add(newEntry: T): boolean
{ +remove(): T
if (anEntry.equals(bag[index]))
{
+remove(anEntry: T): boolean
counter++; +clear(): void
} // end if +getFrequencyOf(anEntry: T): integer
} // end for
} // end getFrequencyOf +contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 32
Implementing More Methods
ArrayBag
• Removing a given entry -bag: T[]
• Search for the entry -numberOfEntries: integer
• Remove the entry from the bag -DEFAULT_CAPACITY: integer
-integrityOK: Boolean
-MAX_CAPACITY: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 33
Implementing More Methods
ArrayBag
• Removing a given entry -bag: T[]
• Search for the entry -numberOfEntries: integer
• Remove the entry from the bag -DEFAULT_CAPACITY: integer
-integrityOK: Boolean
/** Removes one occurrence of a given entry from this bag. -MAX_CAPACITY: integer
@param anEntry The entry to be removed. +getCurrentSize(): integer
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry) +isEmpty(): boolean
{ +add(newEntry: T): boolean
checkIntegrity();
int index = getIndexOf(anEntry); +remove(): T
T result = removeEntry(index); +remove(anEntry: T): boolean
return anEntry.equals(result);
} // end remove
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 34
Implementing More Methods
// Locates a given entry within the array bag.
// Returns the index of the entry, if located, or -1 otherwise.
• Removing a given entry // Precondition: checkIntegrity has been called.
private int getIndexOf(T anEntry)
• Search for the entry {
int where = -1;
• Remove the entry from the bag boolean found = false;
int index = 0;
/** Removes one occurrence of a given entry from this bag. while (!found && (index < numberOfEntries))
@param anEntry The entry to be removed. {
@return True if the removal was successful, or false if not. */ if (anEntry.equals(bag[index]))
public boolean remove(T anEntry) {
{ found = true;
checkIntegrity(); where = index;
int index = getIndexOf(anEntry); } // end if
T result = removeEntry(index); index++;
return anEntry.equals(result); } // end while
} // end remove
// Assertion: If where > -1, anEntry is in the array bag, and it
// equals bag[where]; otherwise, anEntry is not in the array
return where;
} // end getIndexOf 35
Implementing More Methods
• Removing a given entry
• Search for the entry
• Remove the entry from the bag
36
Implementing More Methods
• Removing a given entry
Option 1 Option 2
?
37
Implementing More Methods
• Removing a given entry
• Search for the entry
// Removes and returns the entry at a given index within the array bag.
• Remove the entry from the bag // If no such entry exists, returns null.
// Preconditions: 0 <= givenIndex < numberOfEntries;
// checkIntegrity has been called.
/** Removes one occurrence of a given entry from this bag. private T removeEntry(int givenIndex)
@param anEntry The entry to be removed. {
@return True if the removal was successful, or false if not. */ T result = null;
public boolean remove(T anEntry)
{ if (!isEmpty() && (givenIndex >= 0))
checkIntegrity(); {
int index = getIndexOf(anEntry); result = bag[givenIndex]; // Entry to remove
T result = removeEntry(index); bag[givenIndex] = bag[numberOfEntries - 1]; // Replace entry with last entry
return anEntry.equals(result); bag[numberOfEntries - 1] = null; // Remove last entry
} // end remove numberOfEntries--;
} // end if
return result;
} // end removeEntry
38
Implementing More Methods
ArrayBag
• Removing an unspecified entry -bag: T[]
• Simply remove the last entry -numberOfEntries: integer
-DEFAULT_CAPACITY: integer
-integrityOK: Boolean
/** Removes one unspecified entry from this bag, if possible. -MAX_CAPACITY: integer
@return Either the removed entry, if the removal was successful, +getCurrentSize(): integer
or null otherwise. */
public T remove() +isEmpty(): boolean
{ +add(newEntry: T): boolean
checkIntegrity();
T result = removeEntry(numberOfEntries - 1); +remove(): T
return result; +remove(anEntry: T): boolean
} // end remove
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 39
Implementing More Methods
ArrayBag
-bag: T[]
/** Removes all entries from this bag. */ -numberOfEntries: integer
public void clear()
{ -DEFAULT_CAPACITY: integer
while (!isEmpty()) -integrityOK: Boolean
remove();
} // end clear
-MAX_CAPACITY: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
/** Tests whether this bag contains a given entry. +remove(): T
@param anEntry The entry to locate.
@return True if this bag contains anEntry, or false otherwise. */ +remove(anEntry: T): boolean
public boolean contains(T anEntry) +clear(): void
{
checkIntegrity(); +getFrequencyOf(anEntry: T): integer
return getIndexOf(anEntry) > -1; // or >= 0 +contains(anEntry: T): boolean
} // end contains
+toArray(): T[]
–isArrayFull(): boolean 40
Putting all pieces together to form ArrayBag.java
ArrayBag
-bag: T[]
-numberOfEntries: integer
-DEFAULT_CAPACITY: integer
-integrityOK: Boolean
-MAX_CAPACITY: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
–isArrayFull(): boolean 41
/** An interface that describes the operations of a bag of objects. */
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag, if possible.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to find.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag. Note: If the bag is empty, the
returned array is empty. */
public T[] toArray();
} // end BagInterface BagInterface.java 42
OnlineShopper.java
/** A class that maintains a shopping cart for an online store. */ public class Item
public class OnlineShopper {
{ Item.java private String description;
public static void main(String[] args) private int price;
{
Item[] items = {new Item("Bird feeder", 2050),
new Item("Squirrel guard", 1547), public Item(String productDescription, int productPrice)
new Item("Bird bath", 4499), {
new Item("Sunflower seeds", 1295)}; description = productDescription;
price = productPrice;
BagInterface<Item> shoppingCart = new ArrayBag<>(); } // end constructor
int totalCost = 0;
public String getDescription()
// Statements that add selected items to the shopping cart: {
for (int index = 0; index < items.length; index++)
{ return description;
Item nextItem = items[index]; // Simulate getting item from shopper } // end getDescription
shoppingCart.add(nextItem);
totalCost = totalCost + nextItem.getPrice(); public int getPrice()
} // end for {
return price;
// Simulate checkout } // end getPrice
while (!shoppingCart.isEmpty())
System.out.println(shoppingCart.remove()); public String toString()
System.out.println("Total cost: " + "\t$" + totalCost / 100 + "." + totalCost % 100); {
} // end main return description + "\t$" + price / 100 + "." + price % 100;
} // end OnlineShopper } // end toString
} // end Item
43
Implementations of a Bag
• Using Fixed-Size Arrays Using a fixed-size array to implement the ADT bag,
therefore, limits the size of the bag.
• Using Array Resizing
• Using Linked Data
44
Bag Implementations That Use Array
Resizing
• The process of array resizing
45
Bag Implementations That Use Array
Resizing
• Doubling the size of an array each time it becomes full is a typical approach
46
Bag Implementations That Use Array
Resizing
• Revised method add using array resizing
// Throws an exception if the client requests a capacity that is too large.
/** Adds a new entry to this bag. private void checkCapacity(int capacity)
@param newEntry The object to be added as a new entry. {
@return True. */ if (capacity > MAX_CAPACITY)
public boolean add(T newEntry) throw new IllegalStateException("Attempt to create a bag whose " +
{ "capacity exeeds allowed " +
checkIntegrity(); "maximum of " + MAX_CAPACITY);
boolean result = true; } // end checkCapacity
if (isArrayFull())
{
doubleCapacity();
} // end if // Doubles the size of the array bag.
// Precondition: checkIntegrity has been called.
bag[numberOfEntries] = newEntry; private void doubleCapacity()
numberOfEntries++; {
int newLength = 2 * bag.length;
return true; checkCapacity(newLength);
} // end add bag = Arrays.copyOf(bag, newLength);
} // end doubleCapacity
47
Pros and Cons of Using an Array
• +Adding an entry to the bag is fast
• +Removing an unspecified entry is fast
48
Implementations of a Bag
• Using Fixed-Size Arrays
• Array has fixed size and may become full.
• Alternatively may have wasted space.
• Using Array Resizing
• Resizing is possible but requires overhead of time
• Using Linked Data
49
A Linked Implementation of a Bag
• Node with two data fields
50
A Linked Implementation of a Bag
• Node with two data fields
51
A Linked Implementation of a Bag
• Node with two data fields
52
A Linked Implementation of a Bag
• Organize data by linking it together
53
A Linked Implementation of a Bag
• Organize data by linking it together
LinkedBag
-firstNode: Node
-numberOfEntries: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
55
A Linked Implementation of a Bag
• The method add
56
A Linked Implementation of a Bag
• The method add
• Adding a new node to an empty chain
• Adding a new node to a non-empty chain
57
A Linked Implementation of a Bag
• The method add
• Adding a new node to an empty chain
• Adding a new node to a non-empty chain
58
A Linked Implementation of a Bag
• The method add
• Adding a new node to an empty chain
• Adding a new node to a non-empty chain
59
A Linked Implementation of a Bag
• The method add
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry
@return True if the addition is successful, or false if not. */
return true;
} // end add
60
A Linked Implementation of a Bag
• The method remove
61
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
62
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
63
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
64
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
return result;
} // end remove
65
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
66
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
• Search for the given entry in a bag
• Remove the given entry
67
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
• Search for the given entry in a bag
• Remove the given entry
68
A Linked Implementation of a Bag
• The method remove
• Removing an unspecified entry from a bag
• Removing a given entry from a bag
• Search for the given entry in a bag
• Remove the given entry
Option 1:
10
Option 2:
result = true;
} // end if
return result;
} // end remove
72
A Linked Implementation of a Bag
• The method getFrequencyOf
73
A Linked Implementation of a Bag
• The method contains
74
A Linked Implementation of a Bag
• The method toArray
75
Putting all pieces together to form LinkedBag.java
LinkedBag
-firstNode: Node
-numberOfEntries: integer
+getCurrentSize(): integer
+isEmpty(): boolean
+add(newEntry: T): boolean
+remove(): T
+remove(anEntry: T): boolean
+clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean
+toArray(): T[]
76
/** An interface that describes the operations of a bag of objects. */
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag, if possible.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to find.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag. Note: If the bag is empty, the
returned array is empty. */
public T[] toArray();
} // end BagInterface BagInterface.java 77
LinkedBagDemo.java
…
79
The ADT Set
• A set is a special kind of bag, one that does not allow duplicate entries
<<interface>> <<interface>>
Bag Set
80
The ADT Set
• A set is a special kind of bag, one that does not allow duplicate entries
/** An interface that describes the operations of a set of objects. */
public interface SetInterface<T> <<interface>>
{ Set
public int getCurrentSize();
public boolean isEmpty();
https://www.geeksforgeeks.org/set-in-java/
https://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/ 82
Java Class Library: The Interface Set
https://www.geeksforgeeks.org/set-in-java/ 83
The Interface Set
Readings: https://www.geeksforgeeks.org/set-in-java/
84
Summary
• ADT Bag
• Implementations of a Bag
85
What I Want You to Do
• Review class slides
• Review Chapter 1, Chapter 2, and Chapter 3
• Next Topic
• Efficiency of Algorithms
86