Java Reference
In-Depth Information
they were inserted.
TreeSet
stores elements sorted. All the methods in
HashSet
,
LinkedHashSet
, and
TreeSet
are inherited from the
Collection
interface.
4.
The
Map
interface maps keys to the elements. The keys are like indexes. In
List
,
the indexes are integers. In
Map
, the keys can be any objects. A map cannot contain
duplicate keys. Each key can map to at most one value. The
Map
interface provides
the methods for querying, updating, and obtaining a collection of values and a set
of keys.
5.
Three types of maps are supported:
HashMap
,
LinkedHashMap
, and
TreeMap
.
HashMap
is efficient for locating a value, inserting an entry, and deleting an entry.
LinkedHashMap
supports ordering of the entries in the map. The entries in a
Hash-
Map
are not ordered, but the entries in a
LinkedHashMap
can be retrieved either in
the order in which they were inserted into the map (known as the
insertion order
)
or in the order in which they were last accessed, from least recently accessed to
most recently (
access order
).
TreeMap
is efficient for traversing the keys in a sorted
order. The keys can be sorted using the
Comparable
interface or the
Comparator
interface.
Q
UIZ
P
ROGRAMMING
E
XERCISES
Sections 21.2-21.4
21.1
(
Perform set operations on hash sets
) Create two linked hash sets {
"George"
,
"Jim"
,
"John"
,
"Blake"
,
"Kevin"
,
"Michael"
} and {
"George"
,
"Katie"
,
"Kevin"
,
"Michelle"
,
"Ryan"
} and find their union, difference, and intersec-
tion. (You can clone the sets to preserve the original sets from being changed by
these set methods.)
21.2
(
Display nonduplicate words in ascending order
) Write a program that reads
words from a text file and displays all the nonduplicate words in ascending order.
The text file is passed as a command-line argument.
**21.3
(
Count the keywords in Java source code
) Revise the program in Listing 21.7. If
a keyword is in a comment or in a string, don't count it. Pass the Java file name
from the command line. Assume that the Java source code is correct and line
comments and paragraph comments do not overlap.
*21.4
(
Count consonants and vowels
) Write a program that prompts the user to enter a
text file name and displays the number of vowels and consonants in the file. Use
a set to store the vowels
A
,
E
,
I
,
O
, and
U
.
***21.5
(
Syntax highlighting
) Write a program that converts a Java file into an HTML
file. In the HTML file, the keywords, comments, and literals are displayed in
bold navy, green, and blue, respectively. Use the command line to pass a Java file
and an HTML file. For example, the following command
java Exercise21_05 Welcome.java Welcome.html
converts
Welcome.java
into
Welcome.html
. Figure 21.8a shows a Java file. The
corresponding HTML file is shown in Figure 21.8b.
Search WWH ::
Custom Search