Java中Hashtable toString()方法

Java中Hashtable toString()方法

Java中Hashtable类中的toString()方法返回Hashtable中包含的键-值映射的字符串表示形式。该字符串采用花括号括起来的以逗号分隔的键值对的形式。

toString()方法是从java.util.Dictionary类的父类java.util.Hashtable类继承来的。

这是一个使用toString()方法的例子:

import java.util.Hashtable;
 
public class HashtableExample {
    public static void main(String[] args)
    {
        Hashtable<String, Integer> ht = new Hashtable<>();
        ht.put("Alice", 25);
        ht.put("Bob", 30);
        ht.put("Charlie", 35);
 
        System.out.println(ht.toString());
    }
}

输出

{Bob=30, Charlie=35, Alice=25}

java.util.Hashtable.toString()是Hashtable内置方法,用于以由“,”分隔的一组条目的形式获取Hashtable对象的字符串表示形式。因此,toString()方法用于将Hashtable的所有元素转换为字符串。

语法:

HashTable.toString()

参数: 该方法不含任何参数。
返回值: 该方法返回一个集合,其中包含哈希表元素的字符串表示形式。

下面的程序演示了java.util.Hashtable.toString()方法的工作原理:

程序1:

// Java code to illustrate the toString() method
 
import java.util.*;
 
public class Hash_Table_Demo {
    public static void main(String[] args)
    {
 
        // Creating an empty Hashtable
        Hashtable<Integer, String> hash_table
            = new Hashtable<Integer, String>();
 
        // Inserting elements into the table
        hash_table.put(10, "Geeks");
        hash_table.put(15, "4");
        hash_table.put(20, "Geeks");
        hash_table.put(25, "Welcomes");
        hash_table.put(30, "You");
 
        // Displaying the Hashtable
        System.out.println("Initial table is: "
                           + hash_table);
 
        // Displaying the string representation
        System.out.println("The set is: "
                           + hash_table.toString());
    }
}

输出:

Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The set is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}

程序2:

// Java code to illustrate the toString() method
 
import java.util.*;
 
public class Hash_Table_Demo {
   
    public static void main(String[] args)
    {
 
        // Creating an empty Hashtable
        Hashtable<String, Integer> hash_table
            = new Hashtable<String, Integer>();
 
        // Inserting elements into the table
        hash_table.put("Geeks", 10);
        hash_table.put("4", 15);
        hash_table.put("Geeks", 20);
        hash_table.put("Welcomes", 25);
        hash_table.put("You", 30);
 
        // Displaying the Hashtable
        System.out.println("Initial Table is: "
                           + hash_table);
 
        // Displaying the string representation
        System.out.println("The set is: "
                           + hash_table.toString());
    }

输出:

Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The set is: {You=30, Welcomes=25, 4=15, Geeks=20}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程