Java中的Dictionary.size()方法及示例

Java中的Dictionary.size()方法及示例

Java中Dictionary类中的size()方法用于获取字典的大小或字典中不同键的数量。

语法:

DICTIONARY.size()

参数:

该方法不接受任何参数。

返回值:

该方法返回字典中键的数量。

以下程序演示了size()方法:

程序1:

// Java代码来演示size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // 创建Hashtable类型的字典
        Dictionary<Integer, String> dict
            = new Hashtable<Integer, String>();
  
        // 向字典中插入元素
        dict.put(10, "Geeks");
        dict.put(15, "4");
        dict.put(10, "Geeks");
        dict.put(25, "Welcomes");
        dict.put(30, "You");
  
        // 显示字典
        System.out.println("Dictionary: " + dict);
  
        // 显示字典的大小
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}
Dictionary: {10=Geeks, 30=You, 15=4, 25=Welcomes}
The size of the dictionary is 4

程序2:

// Java代码来演示size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // 创建Hashtable类型的字典
        Dictionary<String, Integer> dict
            = new Hashtable<String, Integer>();
  
        // 向字典中插入元素
        dict.put("Geek", 10);
        dict.put("4", 15);
        dict.put("Geeks", 20);
        dict.put("Welcomes", 25);
        dict.put("You", 30);
  
        // 显示字典
        System.out.println("Dictionary: " + dict);
  
        // 显示字典的大小
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}
Dictionary: {You=30, Welcomes=25, 4=15, Geeks=20, Geek=10}
The size of the dictionary is 5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程