简体   繁体   English

为什么 System.out.println(map.put(1,“test”)) 打印 null 值?

[英]Why does System.out.println(map.put(1,“test”)) print null value?

class Test3 {  
    public static void main(String args[]){  
        Map<Integer, String> aa = new HashMap();
        System.out.println(aa.put(1, "test"));
    }  

}

whenever I execute this statement it prints null value.每当我执行此语句时,它都会打印 null 值。 I want to know why it printing the null value.我想知道为什么它打印 null 值。 What is happening?怎么了?

From the Javadoc of Map.put :来自Map.put的 Javadoc

 V put(K key, V value)

... ...

Returns : the previous value associated with key, or null if there was no mapping for key.返回:与键关联的先前值,如果没有键映射,则返回 null。

The map is empty before the call to put , so "there was no mapping for key", so null is returned. map 在调用put之前为空,因此“没有键映射”,因此返回null

implementation of put is something like below put 的实现如下所示

@Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }

If the map previously contained a mapping for the key, the old value is replaced.如果 map 之前包含密钥的映射,则旧值将被替换。 else null will return because there is no mapping.否则 null 将返回,因为没有映射。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Java 中的 System.out.println() 会打印到控制台? - Why does System.out.println() in Java print to the console? System.out.println为什么打印新行而System.out.print什么都不打印? - Why does System.out.println print a new line while System.out.print prints nothing? 为什么`System.out.println(null);`give“方法println(char [])对于类型PrintStream错误是不明确的”? - Why does `System.out.println(null);` give “The method println(char[]) is ambiguous for the type PrintStream error”? System.out.println() 不会打印到 Eclipse 中的控制台 - System.out.println() does not print to the console in Eclipse 为什么System.out.println()不打印字符串 - Why System.out.println() doesn't print the string 在使用System.out.println()打印集时为什么要并发修改异常? - Why concurrentmodificationexception when print a set with System.out.println()? 为什么/什么时候 System.out.println(); 给出错误:方法打印(布尔)...不适用 - Why/when does System.out.println(); give error: method print(boolean)...not applicable 为什么 System.out.println(“0:00”.compareTo(“0”)); 结果是3? - Why does System.out.println(“0:00”.compareTo(“0”)); result in 3? 为什么 System.out.println(&#39;a&#39; == 97.0) 给出 true - Why does System.out.println('a' == 97.0) give true 在 Java 中,为什么 System.out.println(“\\” \\\\“); 给出“\\”作为输出 - In Java, why does System.out.println(“\” \\“); gives ” \ as output
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM