The Class BagOfStrings So Far
In this lesson, we will collect the constructor and method definitions into a class and test it.
We'll cover the following...
The class and a client
The following program shows the definition of the class BagOfStrings
at this point in its development. It contains only the data fields, constructors, and core methods that we have seen earlier. Before we continue the implementation of this class, we will test the class using the method main
in the class BagDemo1
, which is also in the code given below. Click the RUN button.
Press + to interact
BagDemo1.java
BagOfStrings.java
/**A class that partially implements a bag of strings by using an array.@author Frank M. Carrano*/public class BagOfStrings{private static final int DEFAULT_CAPACITY = 25;private String[] bag;private int numberOfStrings;/** Creates an empty bag whose capacity is 25. */public BagOfStrings(){this(DEFAULT_CAPACITY);} // End default constructor/** Creates an empty bag having a given capacity.@param capacity The integer capacity desired. */public BagOfStrings(int capacity){bag = new String[capacity];numberOfStrings = 0;} // End constructor/** Adds a new string to this bag.@param newString The string to be added.@return true if the addition is successful, or false if not. */public boolean add(String newString){boolean result = true;if (isFull()){result = false;}else{ // Assertion: result is true herebag[numberOfStrings] = newString;numberOfStrings++;} // End ifreturn result;} // End add/** Retrieves all strings that are in this bag.@return a newly allocated array of all the strings in this bag. */public String[] toArray(){String[] result = new String[numberOfStrings];for (int index = 0; index < numberOfStrings; index++){result[index] = bag[index];} // End forreturn result;// Note: The body of this method could consist of one return statement,// if you call Arrays.copyOf} // End toArray/** Sees whether this bag is full.@return true if this bag is full, or false if not */public boolean isFull(){return numberOfStrings == bag.length;} // End isFull} // End BagOfStrings
After running the previous program, you should get the following output:
Adding to an empty bag: A, A, B, A, C, A The bag contains A A B A C A This bag is not full. Adding to an empty bag: A, B, A, C, B, C, D The bag contains A B A...