Java Reference
In-Depth Information
set of words. Technically, this will be a set of strings, where each string in the set represents a
single word that was entered by the user.
If we can do that, then we can pass the whole set to the Responder , which can then check
every word in the set to see whether it is known and has an associated response.
To achieve this in Java, we need to know about two things: how to cut a single string containing
a whole sentence into words and how to use sets. These two issues are discussed in the next two
Using sets
The Java standard library includes different variations of sets implemented in different classes.
The class we shall use is called HashSet .
Exercise 5.34 What are the similarities and differences between a HashSet and an
ArrayList ? Use the descriptions of Set , HashSet , List , and ArrayList in the library
documentation to find out, because HashSet is a special case of a Set and ArrayList is a
special case of a List .
The two types of functionality that we need are the ability to enter elements into the set and re-
trieve the elements later. Fortunately, these tasks contain hardly anything new for us. Consider
the following code fragment:
import java.util.HashSet;
HashSet<String> mySet = new HashSet<String>();
Compare this code with the statements needed to enter elements into an ArrayList . There is
almost no difference, except that we create a HashSet this time instead of an ArrayList . Now
let us look at iterating over all elements:
for(String item : mySet) {
do something with that item
Again, these statements are the same as the ones we used to iterate over an ArrayList in
Chapter 4.
A set is a collection
that stores each
individual element
at most once. It
does not maintain
any specific order.
In short, using collections in Java is quite similar for different types of collections. Once you
understand how to use one of them, you can use them all. The differences really lie in the
behavior of each collection. A list, for example, will keep all elements entered in the desired
order, provides access to elements by index, and can contain the same element multiple times.
Search WWH ::

Custom Search