Map 接口中还有一个实现类 Hashtable,它和 HashMap 十分相似,区别在于 Hashtable 是线程安全的。Hashtable 存取元素时速度很慢,目前基本上被 HashMap 类所取代,但 Hashtable 类有一个子列 Properties,在实际应用中非常重要。
    Properties 主要用来存储字符串类型的键和值,在实际开发中,经常使用 Properties 集合来存取应用的配置项。假设有一个文本编辑工具,要求默认背景色是红色,字体大小为 14px,语言为中文,其配置项如下。

    1. Backgroup-color = red
    2. Font-size = 14px
    3. Language = chinese

    在程序中可以使用 Properties 集合对这些配置项进行存取,接下来通过一个案例来学习 Properites 集合的使用。

    1. import java.util.Enumeration;
    2. import java.util.Properties;
    3. public class example15 {
    4. public static void main(String[] args) {
    5. //创建 Properties 集合
    6. Properties properties = new Properties();
    7. properties.setProperty("Backgroup-color","red"); //存储键和值,等价于 put()
    8. properties.setProperty("Font-size","14px");
    9. properties.setProperty("Language","chiniese");
    10. //获取集合中所有的键
    11. Enumeration names = properties.propertyNames(); //Enumeration 等价于 Iterator 迭代器
    12. //循环遍历所有的键
    13. while (names.hasMoreElements()) { //判断是否有下一个元素可以获取,等价于 hasNext()
    14. String key = (String) names.nextElement(); //默认是 object 类型,这里需要进行类型转换,转换成 string 类型
    15. String value = properties.getProperty(key); //获取对应键的值,等价于 get()
    16. System.out.println(key + " = " + value);
    17. }
    18. }
    19. }
    20. console:
    21. Language = chiniese
    22. Backgroup-color = red
    23. Font-size = 14px

    Properties 类中,针对字符串的存取提供了两个专用的方法:setProperty() getProperty()。setProperty()方法用于将配置项的键和值添加到 Properties 集合当中。在第十行代码中通过调用 Properites 的 propertyNames()方法得到一个包含所有键的 Enumeration 对象,然后在遍历所有的键时,通过调用 getProperty()方法获得键所对应的值。注释里有注解,回顾时多多留意。