Java Reference
In-Depth Information
Here, in addition to using a HashSet , we also use the split method, which is a standard
method of the String class.
The split method can divide a string into separate substrings and return those in an array
of strings. The parameter to the split method defines at what kind of characters the original
string should be split. We have defined that we want to cut our string at every space character.
The next few lines of code create a HashSet and copy the words from the array into the set
before returning the set. 3
Exercise 5.35 The split method is more powerful than it first seems from our example.
How can you define exactly how a string should be split? Give some examples.
Exercise 5.36 How would you call the split method if you wanted to split a string at
either space or tab characters? How might you break up a string in which the words are sepa-
rated by colon characters (:)?
Exercise 5.37 What is the difference in the result of returning the words in a HashSet
compared with returning them in an ArrayList ?
Exercise 5.38 What happens if there is more than one space between two words (e.g.,
two or three spaces)? Is there a problem?
Exercise 5.39 Challenge exercises Read the footnote about the Arrays.asList
method. Find and read the sections in this topic about class variables and class methods.
Explain in your own words how this works.
What are examples of other methods that the Arrays class provides?
Create a class called SortingTest . In it, create a method that accepts an array of int val-
ues as a parameter and prints out to the terminal the elements sorted (smallest element first).
Finishing the TechSupport system
To put everything together, we also have to adjust the SupportSystem and Responder
classes to deal correctly with a set of words rather than a single string. Code 5.6 shows the new
version of the start method from the SupportSystem class. It has not changed a great deal.
The changes are:
3 There is a shorter, more elegant way of doing this. One could write
HashSet<String> words = new HashSet<String>(Arrays.asList(wordArray));
to replace all four lines of code. This uses the Arrays class from the standard library and a static
method (also known as class method ) that we do not really want to discuss just yet. If you are curious,
read about class methods in Section 6.15, and try to use this version.
Search WWH ::

Custom Search