Java - 枚举 toString() 方法



描述

Java Enum toString() 方法返回此枚举常量的名称,该名称包含在声明中。

声明

以下是java.lang.Enum.toString() 方法的声明

public String toString()

参数

返回值

此方法返回此枚举常量的名称。

异常

获取枚举的字符串表示示例

以下示例演示了枚举的 toString() 方法的用法。

package com.tutorialspoint;

// enum showing programming languages
enum Language {
   C, Java, PHP;
}
public class EnumDemo {
   public static void main(String args[]) {

      // returns the name and hashCode of this enum constant
      System.out.print("Programming in " + Language.C.toString());      
      System.out.println(", Hashcode = " + Language.C.hashCode()); 
      System.out.print("Programming in " + Language.Java.toString());  
      System.out.println(", Hashcode = " + Language.Java.hashCode()); 
      System.out.print("Programming in " + Language.PHP.toString());  
      System.out.println(", Hashcode = " + Language.PHP.hashCode());    
   }
} 

输出

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

Programming in C, Hashcode = 112810359
Programming in Java, Hashcode = 205029188
Programming in PHP, Hashcode = 1309552426

获取枚举的字符串表示示例

以下示例演示了不同枚举的 toString() 方法的另一种用法。

package com.tutorialspoint;

// enum showing topics covered under Tutorials
enum Tutorials {  
   Java, HTML, Python; 
} 
 
public class EnumDemo { 
   public static void main(String args[]) { 
      Tutorials t1, t2, t3;     
      t1 = Tutorials.Java; 
      t2 = Tutorials.HTML; 
      t3 = Tutorials.Python; 
    
      System.out.print("Programming in " + t1.toString());      
      System.out.println(", Hashcode = " + t1.hashCode()); 
      System.out.print("Programming in " + t2.toString());  
      System.out.println(", Hashcode = " + t2.hashCode()); 
      System.out.print("Programming in " + t3.toString());  
      System.out.println(", Hashcode = " + t3.hashCode());
   } 
} 

输出

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

Programming in Java, Hashcode = 112810359
Programming in HTML, Hashcode = 205029188
Programming in Python, Hashcode = 1309552426
java_lang_enum.htm
广告