欢迎访问宙启技术站
智能推送

JavaHashMap类函数:put()

发布时间:2023-07-06 08:01:39

HashMap类的put()方法是用来把指定的键值对添加到HashMap中的。它的签名如下:

V put(K key, V value)

其中,K是键的数据类型,V是值的数据类型。put()方法把指定的键值对添加到HashMap中,并返回该键对应的旧值。如果键已经存在于HashMap中,则新值将替换旧值,并返回旧值。如果键不存在于HashMap中,则键值对将被添加到HashMap中,并且返回null。

put()方法的实现步骤如下:

1. 首先,计算键的哈希码(hash code),使用hashCode()方法。

2. 然后,根据哈希码和HashMap的容量计算出对应的bucket(桶)的索引值。

3. 如果该桶上已经存在键值对,则需要进行冲突解决。常见的解决冲突的方法是使用链表或红黑树。

4. 如果键已经存在于HashMap中,则更新对应的值,并返回旧值。

5. 如果键不存在于HashMap中,则将键值对添加到HashMap中,并返回null。

需要注意的是,如果键的数据类型是自定义类,则需要保证该类正确实现了hashCode()和equals()方法,以保证HashMap能正确找到对应的键。

put()方法的时间复杂度是O(1),但在进行冲突解决时可能会引起链表或红黑树的查找操作,时间复杂度为O(n)。

下面是一个示例代码:

import java.util.HashMap;

public class Example {
    public static void main(String[] args) {
        // 创建一个HashMap对象
        HashMap<Integer, String> map = new HashMap<>();

        // 在HashMap中插入键值对
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");

        // 从HashMap中获取键值对
        System.out.println(map.get(1)); // 输出:One
        System.out.println(map.get(4)); // 输出:null

        // 更新HashMap中的键值对
        map.put(1, "New One");
        System.out.println(map.get(1)); // 输出:New One

        // 遍历HashMap中的键值对
        for (HashMap.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

这个示例代码创建了一个HashMap对象,并使用put()方法向其中插入了三个键值对。之后通过get()方法查询键对应的值,并使用put()方法更新了某个键对应的值。最后使用entrySet()方法遍历了HashMap中的所有键值对。