首页 > 技术文章 > day17-Map集合

zhiai007 2018-08-06 22:07 原文

一、Map集合

  |----Map接口下的集合,都是使用键值对(key-value)的形式存储的.允许null作为键和值。要保证key的唯一性,不重复,重复的key时候,相应的value会被覆盖。

1.HashMap:

  (1) 底层实现原理:底层是一个hash的数据结构(一个table数组和一个entry单链表),在存储元素的时候,先根据key算出hash地址,再找到table数组中的索引位置,根据索引的位置,找到该索引下对应的一个entry链表,再将key值跟entry链表中的每一个节点的key进行对比,如果key相同,则将新的value覆盖旧的value,如果key不同,就将新的键值对存入,并且放在改链表的头部。

 

 (2)当HashMap中存放的元素想要根据自己的规则排序,可以使用Collections工具类中的一个sort方法,但是此方法仅接收一个List集合,和一个比较器,因此在使用前要将Map转成List。

public static void main(String[] args) {
        
        Map<Product,Integer > map = new HashMap<>();
        map.put(new Product("电子",20), 1);
        map.put(new Product("手机",1000), 2);
        map.put(new Product("电脑",2000), 3);
        map.put(new Product("打火机",5), 4);
        map.put(new Product("打火机",5), 5);
        
        
        for (Map.Entry<Product,Integer> temp : map.entrySet()) {
            System.out.println(temp);
        }
        System.out.println();
    
        //将Map转成List
        List<Map.Entry<Product, Integer>> list = new ArrayList<>(map.entrySet());
        //使用Collections工具类中的sort方法,指定一个比较器
        Collections.sort(list, new Comparator<Map.Entry<Product, Integer>>() {

            @Override
            public int compare(Entry<Product, Integer> o1, Entry<Product, Integer> o2) {
                //在Product中已经重写了compareTo方法
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        
        System.out.println("按照价格升序");
        for (Entry<Product, Integer> entry : list) {    
            System.out.println(entry);
        }
        
        System.out.println();
        List<Map.Entry<Product, Integer>> list1 = new ArrayList<>(map.entrySet());
        //自定义一个比较器类实现Comparator接口
        Collections.sort(list1, new MyComparator());
        
        System.out.println("按照存入的value顺序");
        for (Entry<Product, Integer> entry : list1) {
            
            System.out.println(entry);
        }
    }

(3)hashCode方法和equals方法都跟TreeSet集合的一样的。

2.TreeMap:底层是一个红黑树实现的,TreeMap使用基本跟HashMap类似,不同的是TreeMap会有一个自动排序的(根据键的自然顺序),也可以自定义比较器,指定比较规则,跟TreeSet使用比较器一致

3.LinkedHashMap:底层是一个链表实现的,且该集合是存储跟取出的顺序一致的集合。使用较少(需要时候很好用)

推荐阅读