Map集合

40 阅读3分钟

Map集合

map有时被称为字典,或关联数组。将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值

Map集合的特点:

  1. Map集合是一个双列集合,一个元素包含两个值(一个key,一个value)。
  2. Map集合中的元素,key和value的数据类型可以相同,也可以不相同。
  3. Map集合中的元素,key是不允许重复的,value是可以重复的。
  4. Map集合中的元素,key和value是一一对应。

Map遍历的两种方式:

public class Demo01 {
  public static void main(String[] args) {
    Map<String, String[]> map = new HashMap<>();
    map.put("重庆",new String[]{"南川","綦江"});
    map.put("贵州",new String[]{"贵阳","桐梓"});

    System.out.println("==========entrySet==========");

    //使用Set<Map.Entry<K,V>> entrySet()遍历
    for(Map.Entry<String,String[]> entry:map.entrySet() ){
      for(String arr:entry.getValue() ){
        System.out.println(entry.getKey()+"="+arr);
      }
    }

    System.out.println("=========KeySet===========");

    //使用Set<K> keySet()遍历
    for(String key:map.keySet() ){
      for(String arr:map.get(key)){
        System.out.println(key+"="+arr);
      }

    }

    System.out.println("=========iterator or entrySet===========");

    //使用entrySet()+迭代器遍历
    Set<Map.Entry<String, String[]>> set = map.entrySet();
    Iterator<Map.Entry<String, String[]>> iterator = set.iterator();

    while(iterator.hasNext()){
      Map.Entry<String, String[]> entry = iterator.next();
      for(String arr:entry.getValue() ){
        System.out.println(entry.getKey()+"="+arr);
      }
    }

    System.out.println("=========iterator or KeySet===========");

    //使用keySet()+迭代器遍历
    Set<String> strings = map.keySet();
    Iterator<String> it = strings.iterator();

    while (it.hasNext()){
      String next = it.next();
      for(String arr:map.get(next)){
        System.out.println(next+"="+arr);
      }
    }
  }
}

HashMap集合

该类是一个线程不安全的实例,所以HashMap比Hashtable的性能高一点。多个线程访问map对象,使用Hashtable类更好。

由于HashMap里的key不能重复,所以HashMap里最多只有一个key-value对的key为null,但可以由无数多个key-value对的value为null。

Hashtable集合

该类是一个线程安全的map实现,不允许使用null作为key和value,但HashMap可以使用null作为key或value。

LinkedHashMap集合

底层是双向链表,该链表负责维护Map的迭代顺序,迭代顺序与key-value对的插入顺序保持一致。

Properties集合

读写属性文件

SortedMap集合

该集合是Map的一个子接口。

TreeMap集合

该集合实现了Sorted集合。底层是红黑树数据结构

WeakHashMap集合

WeakHashMap与HashMap的用法基本相似,HashMap的key保留了对实际对象的强引用,这意味着只要该HashMap对象不被销毁,HashMap的所有key所引用的对象就不会被垃圾回收,HashMap也不会自动删除这些key所对应的key-value。但WeakHashMap的key只保留了对实际对象的若引用,这意味着如果WeakHashMap对象的key所引用的对象没有被其他强引用变量所引用,则这些key所引用的对象可能被垃圾回收,WeakHashMap也可能自动删除这些key所对应的key-value。

IdentityHashMap集合

该类要求两个key严格相等时才认为两个key相等。

EnumMap集合

该集合是一个与枚举类一起使用的Map实现,所有的key都必须是单个枚举的枚举值。创建EnumMap时必须显示或隐式指定它对于的枚举类

EnumMap具有如下特征:

1、在内部以数组形式保存,所以这种实现形式非常进奏高效。

2、根据key的自然顺序(即枚举值在枚举类中定义顺序)来维护key-value对的顺序。

3、不允许使用null作为key,但允许使用null作为value。

import java.util.EnumMap;

enum Season{
    SPRING,SUMMER,FALL,WINTER
}
public class EnumMapDemo {
    public static void main(String[] args) {
        EnumMap map = new EnumMap(Season.class);
        map.put(Season.SPRING,"春天");
        map.put(Season.SUMMER,"夏天");
        System.out.println(map);
        //{SPRING=春天, SUMMER=夏天}
    }
}

Map集合的性能分析

综合使用HashMap