Java Reference
In-Depth Information
Method
displayMap
(lines 47-62) displays all the entries in the map. It uses
HashMap
method
keySet
(line 49) to get a set of the keys. The keys have type
String
in the
map
, so
method
keySet
returns a generic type
Set
with type parameter specified to be
String
.
Line 52 creates a
TreeSet
of the keys, in which the keys are sorted. The loop in lines 57-
58 accesses each key and its value in the map. Line 58 displays each key and its value using
format specifier
%-10s
to
left align
each key and format specifier
%10s
to
right align
each
value. The keys are displayed in
ascending
order. Line 61 calls
Map
method
size
to get the
number of key-value pairs in the
Map
. Line 61 also calls
Map
method
isEmpty
, which
returns a
boolean
indicating whether the
Map
is empty.
A
Properties
object is a
persistent
Hashtable
that stores
key-value pairs
of
String
s—assum-
ing that you use methods
setProperty
and
getProperty
to manipulate the table rather than
inherited
Hashtable
methods
put
and
get
. By “persistent,” we mean that the
Properties
object can be written to an output stream (possibly a file) and read back in through an input
stream. A common use of
Properties
objects in prior versions of Java was to maintain ap-
plication-configuration data or user preferences for applications. [
Note:
The
Preferences API
(package
java.util.prefs
) is meant to replace this particular use of class
Properties
but
Class
Properties
extends class
Hashtable<Object,
Object>
. Figure 16.19 demonstrates
several methods of class
Properties
.
Line 13 creates an empty
Properties
table
with no default properties. Class
Prop-
erties
also provides an overloaded constructor that receives a reference to a
Properties
object containing default property values. Lines 16 and 17 each call
Properties
method
setProperty
to store a value for the specified key. If the key does not exist in the
table
,
setProperty
returns
null
; otherwise, it returns the previous value for that key.
1
// Fig. 16.19: PropertiesTest.java
2
// Demonstrates class Properties of the java.util package.
3
import
java.io.FileOutputStream;
4
import
java.io.FileInputStream;
5
import
java.io.IOException;
6
import
java.util.Properties;
7
import
java.util.Set;
8
9
public class
PropertiesTest
10
{
11
public static void
main(String[] args)
12
{
13
Properties table =
new
Properties();
14
15
// set properties
table.setProperty(
"color"
,
"blue"
);
table.setProperty(
"width"
,
"200"
);
16
17
18
19
System.out.println(
"After setting properties"
);
20
listProperties(table);
Fig. 16.19
|
Properties
class of package
java.util
. (Part 1 of 3.)