Java Reference
In-Depth Information
A set, on the other hand, does not maintain any specific order (the elements may be returned in
a for-each loop in a different order from that in which they were entered) and ensures that each
element is in the set at most once. Entering an element a second time simply has no effect.
List, Map, and Set It is tempting to assume that a HashSet must be used in a similar way
to a HashMap . In fact, as we have illustrated, a HashSet is actually much closer in usage to an
ArrayList .
When trying to understand how the various collection classes are used, it helps to pay close at-
tention to their names. The names consist of two parts, e.g.: “Array” “List.” The second half tells
us what kind of collection we are dealing with (List, Map, Set), and the first tells us how it is imple-
mented (for instance, using an array).
For using collections, the type of the collection (the second part) is the more important. We have
discussed before that we can often abstract from the implementation; we do not need to think
about it much. Thus, for our purposes, a HashSet and a TreeSet are very similar. They are both
sets, so they behave in the same way. The difference is only in their implementation, which is im-
portant only when we start thinking about efficiency: one implementation will perform some opera-
tions much faster than another. However, efficiency concerns come much later, and only when we
have either very large collections or applications in which performance is critical.
5.8
Dividing strings
Now that we have seen how to use a set, we can investigate how we can cut the input string
into separate words to be stored in a set of words. The solution is shown in a new version of the
InputReader 's getInput method (Code 5.5).
Code 5.5
The getInput
method returning
a set of words
/**
* Read a line of text from standard input (the text
* terminal), and return it as a set of words.
*
* @return A set of Strings, where each String is one of the
* words typed by the user
*/
public HashSet<String> getInput()
{
System.out.print( "> " ); // print prompt
String inputLine = reader.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split( " " );
// add words from array into hashset
HashSet<String> words = new HashSet<String>();
for (String word : wordArray) {
words.add(word);
}
return words;
}
 
 
Search WWH ::




Custom Search