java.util.HashMap.put() 方法
描述
put(K key, V value) 方法用于将指定值与此映射中的指定键相关联。
声明
以下是 java.util.HashMap.put() 方法的声明。
public V put(K key, V value)
参数
key − 这是与指定值关联的键。
value − 这是要与指定键关联的值。
返回值
该方法调用返回与 key 关联的先前值,如果没有 key 映射,则返回 null。
异常
NA
示例
下面的例子展示了 java.util.HashMap.put() 的用法。
package com.tutorialspoint;
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put(1, "tutorials");
newmap.put(2, "point");
newmap.put(3, "is best");
System.out.println("Map value before change: "+ newmap);
// put new values at key 3
String prevvalue = (String)newmap.put(3,"is great");
// check returned previous value
System.out.println("Returned previous value: "+ prevvalue);
System.out.println("Map value after change: "+ newmap);
}
}
让我们编译并运行上面的程序,这将产生以下结果.
Map value before change: {1=tutorials, 2=point, 3=is best}
Returned previous value: is best
Map value after change: {1=tutorials, 2=point, 3=is great}

