Java Map put()方法及实例
该方法用于将指定的值与该地图中指定的键联系起来。
语法
V put(K key, V value)
参数: 该方法有两个参数,key和value,其中key是左边的参数,value是地图中键的对应值。
返回: 该方法如果存在,则返回与键相关的先前值,否则返回-1。下面的程序显示了int put()方法的实现。
程序1 :
// Java code to show the implementation of
// put method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(3, "Three");
map.put(5, "Five");
map.put(7, "Seven");
map.put(9, "Nine");
System.out.println(map);
}
}
输出
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
程序2: 下面的代码显示了put()的实现。
// Java code to show the implementation of
// put method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("3", "Three");
map.put("5", "Five");
map.put("7", "Seven");
map.put("9", "Nine");
System.out.println(map);
}
}
输出
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
参考资料: Oracle文档