Discussion of Activity 2.9 - Adding methods to the ComputerCollection class

We have asked you to ignore the section at the beginning of ComputerCollection, where we have used some code that has not yet been discussed. This code defines a 'constructor' to intialize an object of type ComputerCollection. You will see more about this kind of code in Unit 3.

The methods that were to be completed were

  1. isInNetwork, which returns true or false according to the value returned by the indexOf method. If indexOf returns a non-negative value, then the searched for computer exists in the computers collection, otherwise it is not found.
    // use the indexOf method to tell if a computer is in the network
    public boolean isInNetwork(String wantedComputer)
    {
       boolean found;
       if (indexOf(wantedComputer) > -1)
       {
          found = true;
       }
       else
       {
          found = false;
       }
       return found;
    }
  2. Keeping track of the number of removals requires no more than incrementing the instance variable storing this information, so at the end of the removeComputer method we require the code:

    numOfRemovals++;

    This must appear within the body of the last if statement, as it should only be performed when a removal is performed.

  3. A method to return the number of removals only needs to return the value stored in the numOfRemovals variable:
    // Method to return the number of removals
    public int getNumOfRemovals()
    {
       return numOfRemovals;
    }
    

Notes

There is another observation that is worth making here, concerning the addComputer method of ComputerCollection. This method copies a reference to an array of Strings called computers. Because strings are immutable, there is no danger that the referenced string can be changed by any other part of the program that has a reference to it. Normally, copying a reference does not guarantee that the object referenced (if any) will not be altered by other parts of the program.