java面试题-2.容器之Map

2022/2/11 1:43:41

本文主要是介绍java面试题-2.容器之Map,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

8.HashMap源码分析?

底层:数组+链表(哈希表)
源码:

// 结点
transient Node<K,V>[] table;
// 每个结点里存储的内容
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;

transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold;
final float loadFactor;

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

// 向hash表中添加数据,即存储对象的过程
public V put(K key, V value) {
    // 步骤一:调用key对象的hashcode()方法,获得hashcode
    return putVal(hash(key), key, value, false, true);
}
// 步骤二:根据hashcode计算出hash值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 起初,hash = hashcode % 数组长度,但是,这种算法由于使用了除法,效率低下,JDK后来改进了算法,首先约定数组长度必须为2的整数幂,这样采用位运算即可实现取余的效果:hash = hashcode & table.length - 1。
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 如果binCount大于等于8-1=7,就将当前链表转变为红黑树,大大提高了效率
                    if (binCount >= TREEIFY_THRESHOLD - 1)
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) {
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1;
    }
    else if (oldThr > 0)
        newCap = oldThr;
    else {
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else {
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

// 取数据过程
public V get(Object key) {
    Node<K,V> e;
    // 第一步:获得key的hashcode,通过hash()散列算法得到hash值,进而定位数组的位置。
    // 第三步:返回equals()为true的结点对象的value对象
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 第二步:在链表上挨个比较key对象,将key对象和链表上所有的结点的key对象比较,直到碰到返回true的结点对象为止
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

9.HashMap中的源码问题?

1. 数组的元素类型是什么?
Map.Entry接口的类型(key, value),
HashMap.Entry内部类型,实现了Map.Entry(key, value, next)
2. 为什么要有链表?
计算每一对映射关系的key的hash值,然后根据hash值决定存到table数组[index]
情况一:两个key的hash值一样,但是equals也不一样--->index相同
情况二:两个key的hash值不一样,equals也不一样,但是通过公式运算后--->index相同
那么table[index]无法存放两个对象,所以只能设计为链表的结构,把他们串起来。
3. 数组的初始化的长度是多少?
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 16
4. 数组是否会扩容?

为什么要扩容?
因为如果不扩容,会导致链表会变得很长,那么它的查询效率,添加的效率整个会降低。
什么情况会扩容?
有一个变量threshold阈值来判断是否需要扩容,当这个threshold达到临界值时,就会考虑扩容,还要看当前添加(key, value)时,是否table[index]==null,
如果table[index]!=null,那么就会扩容,如果table[index]为null,那么本次先不扩容。
DEFAULT_LOAD_FACTOR,默认加载因子为0.75
threshold = table.length * 0.75
第一次:16 * 0.75 = 12,当我们size达到12个,就会考虑扩容。
在jdk1.8中扩容:
第一种:
当某个table[index]的链表的个数达到8个,并且table.length<64,那么会扩容
第二种:
size >= threshold,并且table[index] != null
threshold = table.length * loadFator(默认值DEFAULT_LOAD_FACTOR:0.75)
5.index如何计算?
1.key是null,固定位置[index]=[0]
2.第一步,先用hashcode值通过hash(key)函数得到一个比较分散的"hash值"
第二步,再根据"hash值 & (table.length - 1)得到index在[0, length - 1]范围内。
6.如何避免key重复?
如果key相同,用新值代替旧的值。
具体操作如下:
key相同,先判断hash值,如果hash值相同,判断key的地址或equals值是否相等。
7.新的(key,value)添加道table[index]后,发现table[index]不为空,如何连接?
在jdk1.7中,(key,value)是作为table[index]的头,原来下面的元素作为当前(key,value)的next。
在jdk1.8中,直接连接到该链表的尾部。
8.为什么要从JDK1.8之前的链表设计,修改为链表或红黑树的设计?
当某个链表比较长的时候,查找效率会降低。为了提高查询效率,那么把table[index]下面的链表做调整。
如果table[index]的链表的结点的个数比较少,(8个或以内),就保持链表。如果超过8个,那么就要考虑把链表转为一颗红黑树。
TREEIFY_THRESHOLD:树化阈值,从链表转为红黑树的临界值。
9.什么时候树化?
table[index]下的结点数一达到8个就树化吗?
如果table[index]的节点数量已经达到8个了,还要判断table.length是否达到64,如果没有达到64,先扩容。
演示:
8个->9个,length从16->32
9个->10个,length从32->64
10个->11个,length已经达到64,table[index]就从Node类型转为TreeNode类型,说明树化。
MIN_TREEIFY_CAPACITY:最小树化容量64
10.什么时候从树-->链表?
当你删除结点时,这棵树的结点个数少于6个,会反序列化,变为链表。
UNTREEIFY_THRESHOLD:6
树的结构太复杂,当结点少了以后,就用链表更好。
11.hashCode()和equals()方法的关系?
java中规定两个相同(equals()为true)的对象必须具有相等的hashCode。
因为如果equals()为true而两个对象的hashcode不同;那在整个存储过程中就发生了悖论。
11.HashMap与HashTable的区别?
1.HashMap:线程不安全,效率高。允许key或value为null.
2.HashTable:线程安全,效率低。不允许key或value为null.



这篇关于java面试题-2.容器之Map的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程