Map

作者: kanaSki | 来源:发表于2019-06-21 21:49 被阅读0次

Map接口有HashTable、HashMap及TreeMap实现类

HashMap内部为数组+链表的形式,首先根据key值计算出hashCode,再使用Hash算法计算(如hashCode%数组长度,也可以使用hashCode&(数组长度-1),两种方法的效果一样——前提是第二个方法的数组长度必须是2的整数次幂)出存放在数组哪个位置,如果数组该位置已经存放有元素,则将以链表形式继续存放。当链表长度大于8之后,将转为红黑树的结构。

TreeMap为红黑树的一种具体实现。

import java.util.Map;
import java.util.TreeMap;

public class TestTreeMap {

    public static void main(String[] args) {
        Map<Integer, String> treemap1 = new TreeMap<>();
        treemap1.put(20, "aa");
        treemap1.put(3, "bb");
        treemap1.put(6, "cc");

        /**
         * 结果为:
         * 3=============bb
         * 6=============cc
         * 20=============aa
         * 可以看出TreeMap是有序(通过Comparable接口的compareTo方法)的,而HashMap是无序的
         */
        for (int key : treemap1.keySet()) {
            System.out.println(key + "=============" + treemap1.get(key));
        }

        Map<Emp, String> treemap2 = new TreeMap<>();
        treemap2.put(new Emp(100, "123", 10000), "123");
        treemap2.put(new Emp(200, "456", 20000), "456");
        treemap2.put(new Emp(300, "789", 15000), "789");
        for (Emp emp : treemap2.keySet()) {
            System.out.println(emp.id + "============" + treemap2.get(emp));
        }
    }
}

class Emp implements Comparable<Emp> {
    int id;
    String name;
    double salary;

    public Emp(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    /**
     * 当前对象与o比较
     *
     * @param o
     * @return 负数代表小于,0代表等于,正数代表大于
     */
    @Override
    public int compareTo(Emp o) {
        if (this.salary > o.salary) {
            return 1;
        } else if (this.salary < o.salary) {
            return -1;
        } else {
            return 0;
        }
    }
}

HashMap线程不安全,效率高,允许key或者value为null
HashTable线程安全,效率低,不允许key或者value为null

相关文章

网友评论

      本文标题:Map

      本文链接:https://www.haomeiwen.com/subject/enfpqctx.html