Java Reference
In-Depth Information
When increasing the size of an array, you copy its entries to a larger array. You should expand the array sufficiently
to reduce the impact of the cost of copying. A common practice is to double the size of the array.
A class implementing a single interface that declares the operations of an ADT should define the methods
declared in the interface as its only public methods. However, the class can also define private methods and
protected methods.
E XERCISES
1.
Why are the methods getIndexOf and removeEntry in the class ArrayBag private instead of public?
2.
Implement a method replace for the ADT bag that replaces and returns any object currently in a bag with a
given object.
3.
Revise the definition of the method remove , as given in Segment 2.24, so that it removes a random entry
from a bag. Would this change affect any other method within the class ArrayBag?
4.
Define a method removeEvery for the class ArrayBag that removes all occurrences of a given entry from a bag.
5.
An instance of the class ArrayBag has a fixed size, whereas an instance of ResizableArrayBag does not. Give
some examples of situations where a bag would be appropriate if its size is
a. Fixed.
b. Resizable.
6.
Suppose that you wanted to define a class PileOfBooks that implements the interface described in Project 2 of the
previous chapter. Would a bag be a reasonable collection to represent the pile of topics? Explain.
7.
Consider an instance myBag of the class ResizableArrayBag , as discussed in Segments 2.36 to 2.40. Suppose that
the 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 ?
8.
Define a method at the client level that accepts as its argument an instance of the class ArrayBag and returns an
instance of the class ResizableArrayBag that contains the same entries as the argument bag.
9.
Suppose that a bag contains Comparable objects. Implement the following methods for the class ArrayBag :
The method getMin that returns the smallest object in a bag
The method getMax that returns the largest object in a bag
The method removeMin that removes and returns the smallest object in a bag
The method removeMax that removes and returns the largest object in a bag
10.
Suppose that a bag contains Comparable objects. Define a method for the class ArrayBag that returns a new bag of
items that are less than some given item. The header of the method could be as follows:
public ArrayBag<T> getAllLessThan(Comparable<T> anObject)
Make sure that your method does not affect the state of the original bag.
11.
Define an equals method for the class ArrayBag that returns true when the contents of two bags are the same.
Note that two equal bags contain the same number of entries, and each entry occurs in each bag the same number
of times.
 
Search WWH ::




Custom Search