Java 枚举基础

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习 Java 中的枚举(enums)。枚举是 Java 中的一种特殊数据类型,它允许我们定义一组固定的常量。你将学习如何在 Java 中创建、使用和操作枚举。

创建枚举

  1. ~/project 目录下创建一个名为 StudentResult.java 的新文件。
  2. 添加以下代码以创建一个名为 StudentResult 的枚举:
public enum StudentResult {
    PASS,
    FAIL,
    ABSENT
}

使用枚举

  1. ~/project 目录下创建一个名为 Demo.java 的新文件。
  2. 添加以下代码以创建一个 StudentResult 枚举类型的变量并使用其值:
public class Demo {
    public static void main(String[] args) {
        StudentResult result1 = StudentResult.ABSENT;
        StudentResult result2 = StudentResult.FAIL;
        StudentResult result3 = StudentResult.PASS;

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
  1. 在终端中使用以下命令运行代码:
javac Demo.java && java Demo

在 If-Else 语句中使用枚举

  1. 添加以下代码以在 if-else 语句中使用 StudentResult 枚举:
public class Demo {
    public static void main(String[] args) {
        StudentResult result = StudentResult.FAIL;

        if(result == StudentResult.ABSENT)
            System.out.println("The student was absent for the exam.");

        else if(result == StudentResult.PASS)
            System.out.println("The student passed the exam.");

        else if(result == StudentResult.FAIL)
            System.out.println("The student failed the exam.");
    }
}

在 Switch 语句中使用枚举

  1. 添加以下代码以在 switch 语句中使用 StudentResult 枚举:
public class Demo {
    public static void main(String[] args) {
        StudentResult result = StudentResult.FAIL;

        switch(result) {
            case ABSENT : System.out.println("The Student was absent for the exam.");
            break;

            case PASS : System.out.println("The Student passed the exam.");
            break;

            case FAIL : System.out.println("The Student failed the exam.");
            break;
        }
    }
}

遍历枚举

  1. 添加以下代码以遍历 StudentResult 枚举:
public class Demo {
    public static void main(String[] args) {
        StudentResult[] resultArr = StudentResult.values();

        for(StudentResult sr : resultArr) {
            System.out.println(sr + " at index " + sr.ordinal());
        }
    }
}

使用枚举的 toString() 方法

  1. 添加以下代码以使用枚举的 toString() 方法:
public class Demo {
    public static void main(String[] args) {
        for(StudentResult sr : StudentResult.values()) {
            String resultStr = sr.toString();
            System.out.println("Uppercase: " + resultStr);
            System.out.println("Lowercase: " + resultStr.toLowerCase());
            System.out.println();
        }
    }
}

从字符串创建枚举

  1. 添加以下代码以从字符串创建枚举:
public class Demo {
    public static void main(String[] args) {
        String resultStr = "FAIL";
        StudentResult result = StudentResult.valueOf(resultStr);
        System.out.print("Enum from String: " + result);
    }
}
  1. 在终端中使用以下命令运行代码:
javac Demo.java && java Demo

在类中创建枚举

  1. 添加以下代码以在类中创建枚举并使用它:
public class Student {
    String name;
    StudentResult result;

    // 定义一个枚举类型
    enum StudentResult {
        PASS,
        FAIL,
        ABSENT;
    }

    // 构造函数
    Student(String s, StudentResult sr) {
        name = s;
        result = sr;
    }

    // 枚举 if-else 方法
    public void printResult() {
        if (this.result == StudentResult.ABSENT)
            System.out.println(this.name + " was absent for the exam.");

        else if (this.result == StudentResult.PASS)
            System.out.println(this.name + " passed the exam.");

        else
            System.out.println(this.name + " failed the exam.");
    }

    // 枚举方法
    public boolean wasAbsent() {
        if (this.result == StudentResult.ABSENT)
            return true;
        else
            return false;
    }

    // 主方法
    public static void main(String[] args) {
        Student s1 = new Student("Justin", StudentResult.ABSENT);
        Student s2 = new Student("Jessica", StudentResult.PASS);

        s1.printResult();
        s2.printResult();

        System.out.println("Student s1 was absent: " + s1.wasAbsent());
    }
}
  1. 在终端中使用以下命令运行代码:
javac Student.java && javac Demo.java && java Student

使用 EnumSet

  1. 添加以下代码以使用 EnumSet:
import java.util.EnumSet;

enum StudentResult {
    PASS,
    FAIL,
    ABSENT;
}

public class Demo {
    public static void main(String[] args) {
        EnumSet<StudentResult> resultSet1 = EnumSet.of(StudentResult.FAIL, StudentResult.PASS);
        EnumSet<StudentResult> resultSet2 = EnumSet.allOf(StudentResult.class);

        System.out.println("Enum Set-1: " + resultSet1);
        System.out.print("Enum Set-2: " + resultSet2);
    }
}

使用 EnumMap

  1. 添加以下代码以使用 EnumMap:
import java.util.EnumMap;
import java.util.Map;

enum StudentResult {
    PASS,
    FAIL,
    ABSENT;
}

public class Demo {
    public static void main(String[] args) {
        EnumMap<StudentResult, String> resultMap = new EnumMap<>(StudentResult.class);
        resultMap.put(StudentResult.PASS, "Student Passed the exam");
        resultMap.put(StudentResult.FAIL, "Student Failed the exam");
        resultMap.put(StudentResult.ABSENT, "Student was absent for the exam");

        for (Map.Entry<StudentResult, String> e : resultMap.entrySet())
            System.out.println(e.getKey() + " --> " + e.getValue());
    }
}

总结

在本实验中,你学习了如何创建枚举(enum),如何将其与 if-else 和 switch 语句结合使用,如何遍历枚举,如何使用其 toString() 方法,如何从字符串创建枚举,如何在类中创建枚举,如何使用 EnumSet 高效存储枚举常量,如何使用 EnumMap 存储枚举的键值对,以及如何在枚举中使用具体方法和抽象方法。你还了解到,枚举用于定义一组常量值,并且它们可以提高 Java 的类型安全性。

您可能感兴趣的其他 Java 教程