Implementing More Methods
Explore how to implement essential Java methods for managing a bag of strings using arrays. Understand how to check if the bag is empty, determine its capacity and current size, count string occurrences, and verify if a string is contained within the bag. This lesson helps you develop skills in array manipulation and method design for efficient data structure management.
We'll cover the following...
We'll cover the following...
Now that we can add strings to a bag, we can implement the remaining methods, beginning with the easiest
ones. However, we will postpone the definitions of remove momentarily until we see how to search a bag.
The methods isEmpty, getCapacity, and getCurrentSize
The methods isEmpty, getCapacity, and getCurrentSize have straightforward definitions, as we can see here:
/** Sees whether this bag is empty.
@return true if this bag is empty, or false if not. */
public boolean isEmpty()
{
return numberOfStrings == 0;
} // End isEmpty
/** Gets the capacity of this bag.
@return the integer number of strings that this bag can hold. */
public int getCapacity()
{
return bag.length;
} // End getCapacity
/** Gets the number of strings currently in this bag.
@return the integer number of strings currently in this bag. */
public int getCurrentSize()
{
return numberOfStrings;
} // End getCurrentSize