Map 接口中还有一个实现类 Hashtable,它和 HashMap 十分相似,区别在于 Hashtable 是线程安全的。Hashtable 存取元素时速度很慢,目前基本上被 HashMap 类所取代,但 Hashtable 类有一个子列 Properties,在实际应用中非常重要。
Properties 主要用来存储字符串类型的键和值,在实际开发中,经常使用 Properties 集合来存取应用的配置项。假设有一个文本编辑工具,要求默认背景色是红色,字体大小为 14px,语言为中文,其配置项如下。
Backgroup-color = red
Font-size = 14px
Language = chinese
在程序中可以使用 Properties 集合对这些配置项进行存取,接下来通过一个案例来学习 Properites 集合的使用。
import java.util.Enumeration;
import java.util.Properties;
public class example15 {
public static void main(String[] args) {
//创建 Properties 集合
Properties properties = new Properties();
properties.setProperty("Backgroup-color","red"); //存储键和值,等价于 put()
properties.setProperty("Font-size","14px");
properties.setProperty("Language","chiniese");
//获取集合中所有的键
Enumeration names = properties.propertyNames(); //Enumeration 等价于 Iterator 迭代器
//循环遍历所有的键
while (names.hasMoreElements()) { //判断是否有下一个元素可以获取,等价于 hasNext()
String key = (String) names.nextElement(); //默认是 object 类型,这里需要进行类型转换,转换成 string 类型
String value = properties.getProperty(key); //获取对应键的值,等价于 get()
System.out.println(key + " = " + value);
}
}
}
console:
Language = chiniese
Backgroup-color = red
Font-size = 14px
Properties 类中,针对字符串的存取提供了两个专用的方法:setProperty() 和 getProperty()。setProperty()方法用于将配置项的键和值添加到 Properties 集合当中。在第十行代码中通过调用 Properites 的 propertyNames()方法得到一个包含所有键的 Enumeration 对象,然后在遍历所有的键时,通过调用 getProperty()方法获得键所对应的值。注释里有注解,回顾时多多留意。