java中Hashmap的get方法使用

 更新时间:2021年9月13日 16:00  点击:1973

java中Hashmap的get方法

map中存储的是键值对,也就是说通过set方法进行参数和值的存储,之后通过get“键”的形式进行值的读取。

举例

Map map = new Hashmap();//创建一个map
map.put("key","value");//给map赋值
String vlaues = map.get("key");//获取map中键值为“key”的值
system.out.println(vlaues );//输出结果

以上代码的运行结果:

value;

HashMap中get方法的原理

1、首先向get()方法中传递一个key

2、在get()方法中调用hash(key)

如果key!=null,返回该key的哈希值hash = key.hashCode()^ (h >>> 16),否则返回hash=0

3、在get()方法中调用getNode(hash,key)方法

获取该key的节点,并返回value

4、getNode()方法中

首先要判断Hashtable是否为空且table长度大于0且该hash值对应的table元素不为空,条件成立则判断该节点的哈希值是否等于hash,依次遍历该链表或红黑树,查找key==node.key?返回查找到的节点的value

// JDK源码 
public V get(Object key) {
        Node<K,V> e;
        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;
		//判断hashtable是否为空,key对应的tab[ ]是否为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
			//判断第一个节点的hash,key是否相等
            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);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章