Map的存储问题public class MapDemo

import java.util.*;
public class MapDemo {
public static void main(String[] args)
{
Map map = new HashMap();
method_1(map);
}
public static void method_1(Map map)
{
System.out.println(map.put(8, "wangcai"));
}
为什么这里显示的结果是null

关于put函数的返回值是这么描述的:

The put method returns the previous value associated with key, or null if there was no mapping for key.

意思就是: 如果之前已经有这个key值,则返回与其对应的 value。
如果没有,则返回null。

题目中在输出前,是第一次给key = 8 赋值。 之前没有这个key ,所以返回null。

给一个范例,有助于理解:

import java.util.*;

public class MapDemo {
    public static void main(String[] args) {
        Map map = new HashMap();
        method_1(map);
    }

    public static void method_1(Map map) {

        System.out.println(map.put(8, "wangcai")); //null
        System.out.println(map.put(8, "xxxxxxx")); //之前有8,输出其对应的wangcai
    }
}

此时输出为:

图片说明

用心回答每个问题,如果有帮助,请采纳答案好吗,谢谢~~~

put是添加 你要输出 应该输出的是map

当map中没有key是8的元素,把这个键值对放入map中,返回空值
当map中有一个key是8的元素,把新加入的value覆盖原来的key所对应的value,并且返回原来的value。
你可以做个试验:
往里面再put一个键值对,并且key是8,发现有返回值。
比如:
在后面再加一句:System.out.println(map.put(8, "zhangsan"));这个有返回值,返回值是wangcai

Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

返回null说明map之前的key为null,所以你再put一次,就能得到wangcai了。

 map.put(8, "wangcai");
        System.out.println(map.put(8, "wangcai"));

在map中如果该关键字(即键)已经存在,那么与此关键字相关的新值将取代旧值。方法返回关键字的旧值,如果关键字原先并不存在,则返回null

楼主:返回值返回的是上一次保存的值。key=8第一次保存,返回的结果就是为null