软件编程
位置:首页>> 软件编程>> java编程>> java中Hashmap的get方法使用

java中Hashmap的get方法使用

作者:會挖番薯的pank  发布时间:2023-10-29 13:10:05 

标签:java,Hashmap,get

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方法的原理

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

来源:https://blog.csdn.net/weixin_42321329/article/details/88639305

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com