You are on page 1of 86

CS2400 - Data Structures and Advanced Programming

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

+getCurrentSize(): integer // Get the number of items currently in the bag


+isEmpty(): boolean // See whether the bag is empty
+add(newEntry: T): boolean // Add a given object to the bag
+remove(): T // Remove an unspecified object from the bag
+remove(anEntry: T): boolean // Remove a particular object from the bag, if possible
+clear(): void // Remove all objects from the bag
+getFrequencyOf(anEntry: T): integer // Count the number of times a certain object occurs in the bag
+contains(anEntry: T): boolean // Test whether the bag contains a particular object
+toArray(): T[] // Look at all objects that are in the 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

• By declaring the array bag as a final data


members of the class ArrayBag, we know
that the reference to the array in the
variable bag cannot change.

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.

• Question: Can we use the following?

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.

• Question: Can we use the following?

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

/** Removes one occurrence of a given entry from this bag.


@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry)
{
checkIntegrity();
int index = getIndexOf(anEntry);
T result = removeEntry(index);
return anEntry.equals(result);
} // end remove

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

• -Removing a particular entry requires time to locate the entry


• -Increasing the size of the array requires time to copy its entries

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

Here we simply place Node


class as private class member
inside LinkedBag class 54
A Linked Implementation of a Bag

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. */

public boolean add(T newEntry) // OutOfMemoryError possible


{
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.next = firstNode; // Make new node reference rest of chain
// (firstNode is null if chain is empty)

firstNode = newNode; // New node is at beginning of chain


numberOfEntries++;

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

/** Removes one unspecified entry from this bag, if possible.


@return Either the removed entry, if the removal was successful, or null. */
public T remove()
{
T result = null;
if (firstNode != null)
{
result = firstNode.getData();
firstNode = firstNode.getNextNode(); // Remove first node from chain
numberOfEntries--;
} // end if

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

How can be remove the


given entry easily and
efficiently?

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

Remove the given entry directly by


updating the reference in the entry
before the given entry
69
A Linked Implementation of a Bag
Replace the given entry with entry
• The method remove in first node
• 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 2:

Remove first node


instead
70
// Locates a given entry within this bag. /** Removes one occurrence of a given entry from this bag,
// Returns a reference to the node containing the // if possible.
entry, if located, or null otherwise. @param anEntry The entry to be removed.
private Node getReferenceTo(T anEntry) @return True if the removal was successful, or false
{ otherwise. */
boolean found = false; public boolean remove(T anEntry)
Node currentNode = firstNode; {
boolean result = false;
while (!found && (currentNode != null)) Node nodeN = getReferenceTo(anEntry);
{
if (anEntry.equals(currentNode.getData())) if (nodeN != null)
found = true; {
else // Replace located entry with entry in first node
currentNode = currentNode.getNextNode(); nodeN.setData(firstNode.getData());
} // end while // Remove first node
firstNode = firstNode.getNextNode();
return currentNode;
} // end getReferenceTo numberOfEntries--;

result = true;
} // end if

return result;
} // end remove

• Removing a given entry from a bag


• Search for the given entry in a bag
• Remove the given entry
71
A Linked Implementation of a Bag
• The methods isEmpty, getCurrentSize, and clear

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

The client program can be found in our blackboard 78


Pros and Cons of Using a Chain
• +Bag can grow and shrink in size as necessary.
• +Remove and recycle nodes that are no longer needed
• +Adding new entry to end of array or to beginning of chain both
relatively simple
• +Similar for removal

• -Removing specific entry requires search of chain


• -Chain requires more memory than array of same length

79
The ADT Set
• A set is a special kind of bag, one that does not allow duplicate entries

<<interface>> <<interface>>
Bag Set

+getCurrentSize(): integer +getCurrentSize(): integer


+isEmpty(): boolean +isEmpty(): boolean
+add(newEntry: T): boolean +add(newEntry: T): boolean
+remove(): T +remove(): T
+remove(anEntry: T): boolean +remove(anEntry: T): boolean
+clear(): void +clear(): void
+getFrequencyOf(anEntry: T): integer
+contains(anEntry: T): boolean +contains(anEntry: T): boolean
+toArray(): T[] +toArray(): T[]

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

/** Adds a new entry to this set, avoiding duplicates.


@param newEntry The object to be added as a new entry. +getCurrentSize(): integer
@return True if the addition is successful, or
false if the item already is in the set. */
+isEmpty(): boolean
public boolean add(T newEntry); +add(newEntry: T): boolean
+remove(): T
/** Removes a specific entry from this set, if possible. +remove(anEntry: T): boolean
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
+clear(): void
public boolean remove(T anEntry);
+contains(anEntry: T): boolean
public T remove(); +toArray(): T[]
public void clear();
public boolean contains(T anEntry);
public T[] toArray();
} // end SetInterface
81
Java Class Library: The Interface Set

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

You might also like