Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

initial capacity of myBag is 10. What is the length of the array bag after a. Ad

ID: 3904460 • Letter: I

Question

initial capacity of myBag is 10. What is the length of the array bag after a. Adding 145 entries to myBag? b. Adding an additional 20 entries to myBag? 2. Suppose that you wanted to define a class PileOfBooks that implements the interface Baglnterface. Would a bag be a reasonable collection to represent the pile of books? Explain. Revise the definition of the method remove, as given in ArrayBag, so that it removes a random entry from a bag. a. Would this change affect any other method within the class ArrayBag? Define an equals method for the class ArrayBag that returns true when the contents entries, and each entry occurs in each bag the same number of times. The order of b. 4. of two bags are the same. Note that two equal bags contain the same number of the entries in each array is irrelevant.

Explanation / Answer

1.
a. 160. During the 11th addition, the size of bag becomes doubles to 20. At the 21st addition, the bag’s size increases
to 40. At the 41st addition, it gets double in size again to 80. At the 81st addition, size becomes 160 and becomes stable during the addition of the 145th entry.
b. 320. The array can keep 160 entries. As it contains 145 entries, it can have 15 more before having to double in size again.
2. No. The books in a pile have an order. A bag does not order its entries.
3. Begin the file containing ArrayBag with the following statement:
import java.util.Random;
Add the following data field to ArrayBag:
private Random generator;
Add the following statement to the initializing constructor of ArrayBag:
generator = new Random();
The definition of the method remove follows:
public T remove()
{
T result = removeEntry(generator.nextInt(numberOfEntries));
return result;
} // end remove
4. public boolean equals(Object other)
{
boolean result = false;
if (other instanceof ArrayBag)
{
// The cast is safe here
@SuppressWarnings("unchecked")
ArrayBag<T> otherBag = (ArrayBag<T>)other;
int otherBagLength = otherBag.getCurrentSize();
if (numberOfEntries == otherBagLength) // Bags must contain the same number of objects
{
result = true; // Assume equal
for (int index = 0; (index < numberOfEntries) && result; index++)
{
T thisBagEntry = bag[index];
T otherBagEntry = otherBag.bag[index];
if (!thisBagEntry.equals(otherBagEntry))
result = false; // Bags have unequal entries
} // end for
} // end if
// Else bags have unequal number of entries
} // end if
return result;
} // end equals