数组和集合(四)、Map集合的使用总结

一、概述

  • 键值对,无序
  • 键唯一、值不唯一
  • 只允许存在一个Key为null元素

 

二、实现类

1. HashMap

  • · 无序,数组+链表+红黑树
  • · 非线程安全

2. LinkedHashMap

  • · 有序,双向链表
  • · 非线程安全

3. TreeMap

  • · 有序,使用comparator接口
  • · 非线程安全

4. Hashtable

  • · 无序,数组+链表
  • · 不允许使用null作为key和value
  • · 线程安全,不建议使用

5. Properties

  • · 是Hashtable的子类,用于处理属性文件
  • · key和value都是字符串类型
  • · 线程安全

 

三、Map 的三种遍历方式

1. 使用 keySet 遍历

Set set = map.keySet(); 
for (Object key : set) { 
    System.out.println(map.get(key)); 
}

2. 使用 values 遍历

Collection values = map.values(); 
Iterator iterator = values.iterator(); 
while (iterator.hasNext()){ 
    System.out.println("value " + iterator.next()); 
}

3. 使用 Entry 遍历

Set entrySet = map.entrySet(); 
for (Object o : entrySet) { 
    Map.Entry entry = (Map.Entry) o; 
    System.out.println(entry); //key=value      
    System.out.println(entry.getKey() + " / " + entry.getValue()); 
}
原文地址:https://www.cnblogs.com/wslook/p/9385654.html