这篇文章主要介绍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;
如果key!=null,返回该key的哈希值hash = key.hashCode()^ (h >>> 16),否则返回hash=0
获取该key的节点,并返回value
首先要判断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;
}
以上是“java中Hashmap的get方法怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。