在 Java 中為列舉分配自定義值

Sheeraz Gul 2023年10月12日
在 Java 中為列舉分配自定義值

Java enum 資料型別以語言支援的方式建立和使用常量值。通過定義一組有限的值,enum 變得比 int 或 string 等常量變數更安全。

本教程演示瞭如何在 Java 中使用自定義變數建立 enum

在 Java 中為列舉分配自定義值

讓我們將自定義值附加到列舉並嘗試獲取和列印它們。下面的示例建立了具有相應用法的不同程式語言的列舉

package delftstack;

enum Programming_Usage {
  // enum constructor calling with one custom string value
  PYTHON("DataScience"),
  PHP("WebDevelopment"),
  JAVA("AndroidDevelopment"),
  MATLAB("ImageProcessing");

  // declare the private string to get values later
  private String usage;

  // get usage of programming language method
  public String get_usage() {
    return this.usage;
  }

  // enum constructor
  private Programming_Usage(String usage) {
    this.usage = usage;
  }
}

public class Enum_Value {
  public static void main(String args[]) {
    // This example will print usage with corresponding programming language.
    Programming_Usage[] usages = Programming_Usage.values();

    for (Programming_Usage usage : usages) {
      // use get usage method method to get the values of usage and programming language
      System.out.println(
          "For " + usage.get_usage() + ", we mostly use " + usage.name() + " programming");
    }
  }
}

上面的程式碼將獲取列舉的自定義值並列印具有相應用法的程式語言,其中 name() 是列舉的內建方法,get_usage() 是我們定義的方法。

輸出:

For DataScience, we mostly use PYTHON programming
For WebDevelopment, we mostly use PHP programming
For AndroidDevelopment, we mostly use JAVA programming
For ImageProcessing, we mostly use MATLAB programming
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - Java Enum