Set<String> set = balance.keySet();
// Get an iterator.
Iterator<String> itr = set.iterator();
while(itr.hasNext()) {
str = itr.next();
System.out.println(str + ": " +
balance.get(str));
}
System.out.println();
// Deposit 1,000 into John Doe's account.
bal = balance.get("John Doe");
balance.put("John Doe", bal+1000);
System.out.println("John Doe's new balance: " +
balance.get("John Doe"));
}
}
Properties
Propertiesis a subclass ofHashtable. It is used to maintain lists of values in which the key
is aStringand the value is also aString. ThePropertiesclass is used by many other Java
classes. For example, it is the type of object returned bySystem.getProperties( )when
obtaining environmental values. Although thePropertiesclass, itself, is not generic, several
of its methods are.
Propertiesdefines the following instance variable:
Properties defaults;
This variable holds a default property list associated with aPropertiesobject.Properties
defines these constructors:
Properties( )
Properties(PropertiespropDefault)
The first version creates aPropertiesobject that has no default values. The second creates an
object that usespropDefaultfor its default values. In both cases, the property list is empty.
In addition to the methods thatPropertiesinherits fromHashtable,Propertiesdefines
the methods listed in Table 17-19.Propertiesalso contains one deprecated method:save( ).
This was replaced bystore( )becausesave( )did not handle errors correctly.
One useful capability of thePropertiesclass is that you can specify a default property
that will be returned if no value is associated with a certain key. For example, a default value
can be specified along with the key in thegetProperty( )method—such asgetProperty(“name”,
“default value”). If the “name” value is not found, then “default value” is returned. When
you construct aPropertiesobject, you can pass another instance ofPropertiesto be used as
the default properties for the new instance. In this case, if you callgetProperty(“foo”)on a
givenPropertiesobject, and “foo” does not exist, Java looks for “foo” in the defaultProperties
object. This allows for arbitrary nesting of levels of default properties.
Chapter 17: java.util Part 1: The Collections Framework 497