集合框架学习之——Map

Map<K,V>有两个类型参数:K 是此映射所维护的键的类型,V 是映射值的类型。将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。

Map 接口提供三种collection 视图,允许以键集、值集或键-值映射关系集的形式查看某个映射的内容。映射顺序 定义为迭代器在映射的 collection 视图上返回其元素的顺序。某些映射实现可明确保证其顺序,如 TreeMap 类;另一些映射实现则不保证顺序,如 HashMap 类。

 

注:将可变对象用作映射键时必须格外小心。当对象是映射中某个键时,如果以影响 equals 比较的方式更改了对象的值,则映射的行为将是不确定的。

如果向Map中的同一个键添加值,则之前的值会被覆盖。

Map有两个重要的实现类:HashMap,TreeMap.

一:HashMap是基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

 

遍历HashMap有两种方法。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class 遍历HashMap {
    public static void main(String[] args) {
        HashMap<Student,Integer> stu=new HashMap<>();
        stu.put(new Student("南宫平",19),741);
        stu.put(new Student("郭玉霞",27),570);
        stu.put(new Student("龙布诗",57),702);
        stu.put(new Student("叶秋白",56),670);
        stu.put(new Student("梅吟雪",40),671);

        //1:
        //Set<Map.Entry<K,V>> entrySet()方法返回此映射所包含的映射关系的 Set 视图
        //然后调用getKey()、getValue()方法获取此项对应的键和值
        Set<Map.Entry<Student, Integer>> entries = stu.entrySet();
        for(Map.Entry<Student, Integer> ele:entries){
            System.out.println(ele.getKey()+"\t"+ele.getValue());
        }
        System.out.println("---------------------------");
        //2:
        //Set<K> keySet()方法返回此映射中包含的键的 Set 视图。
        //然后调用get(Object key)方法获取指定键所映射的值
        Set<Student> students = stu.keySet();
        for(Student ele:students){
            System.out.println(ele+"\t"+stu.get(ele));
        }
    }
}

运行结果:

集合框架学习之——Map

 

二:TreeMap

和TreeSet类似,该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。

如果TreeMap的键是自定义对象,并且没有实现Comparable接口,那么编译器就会报错。

TreeMap和HashMap的遍历方法类似,只是TreeMap的键如果是自定义对象时,需要自定义对象实现Comparable接口,下面用代码演示:

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo1 {
    public static void main(String[] args) {
        //自定义对象Student只有name和age两个私有数据成员
        //这里我使用匿名内部类传递比较器,这个比较器是比较年龄
        TreeMap<Student,Integer> treeMap=new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student a, Student b) {
                int num=a.getAge()-b.getAge();
                int num2=num==0?a.getName().compareTo(b.getName()):num;
                return num2;
            }
        });
        treeMap.put(new Student("苏蓉蓉",22),2);
        treeMap.put(new Student("姬冰雁",24),4);
        treeMap.put(new Student("原随云",22),6);
        treeMap.put(new Student("胡铁花",25),3);
        treeMap.put(new Student("楚留香",23),5);

        Set<Map.Entry<Student, Integer>> entries = treeMap.entrySet();
        for(Map.Entry<Student, Integer> ele:entries){
            System.out.println(ele.getKey()+"   "+ele.getValue());
        }

    }
}

运行结果:

集合框架学习之——Map