Map用于保存具有映射关系的数据。
Map的子类非常的相似HashMap,LinkedHashMap,SortedMap,TreeMap,EnumMap,只是后缀的不同。
很多人都说Hashtable是线程安全的,HashMap是线程不安全的,这是没错。但Hashtable是个古老的东西,连命名都不规则。现在可以利用Collections工具类来弥补HashMap的线程问题,所以尽量少用,我就不介绍Hashtable了。
先说下LinkedHashMap,他会维护元素的插入顺序,eg
- public class TestLinkedHashMap
- {
- public static void main(String[] args)
- {
- LinkedHashMap scores = new LinkedHashMap();
- scores.put("语文" , 80);
- scores.put("数学" , 76);
- scores.put("英文" , 76);
- //遍历scores里的所有的key-value对
- for (Object key : scores.keySet())
- {
- System.out.print(key + "------>");
- System.out.print(scores.get(key) + "/n");
- }
- }
- }
其实Properties类也是Map只是多了点解析.properties和.xml的功能,eg
- public class TestProperties
- {
- public static void main(String[] args) throws Exception
- {
- Properties props = new Properties();
- //向Properties中增加属性
- props.setProperty("username" , "yeeku");
- props.setProperty("password" , "123456");
- //将Properties中的属性保存到a.ini文件中
- props.store(new FileOutputStream("a.ini") , "comment line");
- //新建一个Properties对象
- Properties props2 = new Properties();
- //向Properties中增加属性
- props2.setProperty("gender" , "male");
- //将a.ini文件中的属性名-属性值追加到props2中
- props2.load(new FileInputStream("a.ini") );
- System.out.println(props2);
- }
- }
学习Map的时候大家可以类比下Set,也可以参看我前面的博客,我只是贴点例子作为大家的参考,学习集合没什么好办法,主要是多用。eg
- //R类,重写了equals方法,如果count属性相等返回true
- //重写了compareTo(Object obj)方法,如果count属性相等返回0;
- class R implements Comparable
- {
- int count;
- public R(int count)
- {
- this.count = count;
- }
- public String toString()
- {
- return "R(count属性:" + count + ")";
- }
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
- return true;
- }
- if (obj != null
- && obj.getClass() == R.class)
- {
- R r = (R)obj;
- if (r.count == this.count)
- {
- return true;
- }
- }
- return false;
- }
- public int compareTo(Object obj)
- {
- R r = (R)obj;
- if (this.count > r.count)
- {
- return 1;
- }
- else if (this.count == r.count)
- {
- return 0;
- }
- else
- {
- return -1;
- }
- }
- }
- public class TestTreeMap
- {
- public static void main(String[] args)
- {
- TreeMap tm = new TreeMap();
- tm.put(new R(3) , "轻量级J2EE企业应用实战");
- tm.put(new R(-5) , "Struts2权威指南");
- tm.put(new R(9) , "ROR敏捷开发最佳实践");
- System.out.println(tm);
- //返回该TreeMap的第一个Entry对象
- System.out.println(tm.firstEntry());
- //返回该TreeMap的最后一个key值
- System.out.println(tm.lastKey());
- //返回该TreeMap的比new R(2)大的最小key值。
- System.out.println(tm.higherKey(new R(2)));
- //返回该TreeMap的比new R(2)小的最大的key-value对。
- System.out.println(tm.lowerEntry(new R(2)));
- //返回该TreeMap的子TreeMap
- System.out.println(tm.subMap(new R(-1) , new R(4)));
- }
- }