欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java中Hashmap的get方法使用

时间:2022-02-24 10:45:37|栏目:JAVA代码|点击:

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;
    }

上一篇:idea将项目上传到Gitee的图文过程

栏    目:JAVA代码

下一篇:springboot实现打印彩色日志

本文标题:java中Hashmap的get方法使用

本文地址:http://www.codeinn.net/misctech/194409.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有