Java Dictionary put()方法及实例

Java Dictionary put()方法及实例

Dictionary的put()方法用于在字典中插入一个映射。这意味着一个特定的键和值可以被映射到一个特定的字典中。

语法

DICTIONARY.put(key, value)

参数: 该方法需要两个参数,都是字典的对象类型。

  • key。 这指的是需要插入到字典中进行映射的关键元素。
  • value。 这指的是上述钥匙将映射成的值。

返回值: 该方法返回键被映射到的值。如果键没有被映射成任何值,则返回NULL。

下面的程序用来说明java.util.Dictionary.put()方法的工作:

程序1 :

// Java code to illustrate the put() method
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Dictionary
        Dictionary<Integer, String> dict
            = new Hashtable<Integer, String>();
  
        // Inserting values into the Dictionary
        dict.put(10, "Geeks");
        dict.put(15, "4");
        dict.put(20, "Geeks");
        dict.put(25, "Welcomes");
        dict.put(30, "You");
  
        // Displaying the Dictionary
        System.out.println("Initial Dictionary is: " + dict);
  
        // Inserting existing key along with new value
        String returned_value = (String)dict.put(20, "All");
  
        // Verifying the returned value
        System.out.println("Returned value is: " + returned_value);
  
        // Displaying the new table
        System.out.println("New Dictionary is: " + dict);
    }
}

输出。

Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: Geeks
New Dictionary is: {10=Geeks, 20=All, 30=You, 15=4, 25=Welcomes}

程序2

// Java code to illustrate the put() method
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Dictionary
        Dictionary<Integer, String> dict
            = new Hashtable<Integer, String>();
  
        // Inserting values into the Dictionary
        dict.put(10, "Geeks");
        dict.put(15, "4");
        dict.put(20, "Geeks");
        dict.put(25, "Welcomes");
        dict.put(30, "You");
  
        // Displaying the Dictionary
        System.out.println("Initial Dictionary is: " + dict);
  
        // Inserting existing key along with new value
        String returned_value = (String)dict.put(50, "All");
  
        // Verifying the returned value
        System.out.println("Returned value is: " + returned_value);
  
        // Displaying the new table
        System.out.println("New Dictionary is: " + dict);
    }
}

输出。

Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: null
New Dictionary is: {10=Geeks, 20=Geeks, 30=You, 50=All, 15=4, 25=Welcomes}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程