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.