Java Hashtable toString() 方法



描述

Java Hashtable toString() 方法用于获取此 Hashtable 对象的字符串表示形式,其形式为一组条目。

声明

以下是 java.util.Hashtable.toString() 方法的声明。

public String toString()

参数

返回值

方法调用返回此哈希表的字符串表示形式。

异常

获取整数、整数对 HashTable 的字符串表示形式示例

以下示例演示了如何使用 Java Hashtable toString() 方法获取 Hashtable 的字符串表示形式。我们创建了一个整数、整数对的 Hashtable 对象。然后使用 put() 方法添加了一些条目,然后使用 toString() 方法打印表的字符串表示形式。

package com.tutorialspoint;

import java.util.Hashtable;

public class HashtableDemo {
   public static void main(String args[]) {
      
      // create hash table
      Hashtable<Integer,Integer> hashtable = new Hashtable<>();

      // populate hash table
      hashtable.put(1, 1);
      hashtable.put(2, 2);
      hashtable.put(3, 3); 

      System.out.println("Hashtable string representation: " + hashtable.toString());
   }    
}

输出

让我们编译并运行上述程序,这将产生以下结果。

Hashtable string representation: {3=3, 2=2, 1=1}

获取整数、字符串对 HashTable 的字符串表示形式示例

以下示例演示了如何使用 Java Hashtable toString() 方法获取 Hashtable 的字符串表示形式。我们创建了一个整数、字符串对的 Hashtable 对象。然后使用 put() 方法添加了一些条目,然后使用 toString() 方法打印表的字符串表示形式。

package com.tutorialspoint;

import java.util.Hashtable;

public class HashtableDemo {
   public static void main(String args[]) {
      
      // create hash table
      Hashtable<Integer,String> hashtable = new Hashtable<>();

      // populate hash table
      hashtable.put(1, "tutorials");
      hashtable.put(2, "point");
      hashtable.put(3, "is best"); 

      System.out.println("Hashtable string representation: " + hashtable.toString());
   }    
}

输出

让我们编译并运行上述程序,这将产生以下结果。

Hashtable string representation: {3=is best, 2=point, 1=tutorials}

获取整数、对象对 HashTable 的字符串表示形式示例

以下示例演示了如何使用 Java Hashtable toString() 方法获取 Hashtable 的字符串表示形式。我们创建了一个整数、Student 对的 Hashtable 对象。然后使用 put() 方法添加了一些条目,然后使用 toString() 方法打印表的字符串表示形式。

package com.tutorialspoint;

import java.util.Hashtable;

public class HashtableDemo {
   public static void main(String args[]) {
      
      // create hash table
      Hashtable<Integer,Student> hashtable = new Hashtable<>();

      // populate hash table
      hashtable.put(1, new Student(1, "Julie"));
      hashtable.put(2, new Student(2, "Robert"));
      hashtable.put(3, new Student(3, "Adam"));

      System.out.println("Hashtable string representation: " + hashtable.toString());
   }    
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果。

Hashtable string representation: {3=[ 3, Adam ], 2=[ 2, Robert ], 1=[ 1, Julie ]}
java_util_hashtable.htm
广告

© . All rights reserved.